clang  19.0.0git
SemaDeclCXX.cpp
Go to the documentation of this file.
1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements semantic analysis for C++ declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/RecordLayout.h"
27 #include "clang/AST/StmtVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/AST/TypeOrdering.h"
32 #include "clang/Basic/Specifiers.h"
33 #include "clang/Basic/TargetInfo.h"
35 #include "clang/Lex/Preprocessor.h"
37 #include "clang/Sema/DeclSpec.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/Ownership.h"
43 #include "clang/Sema/Scope.h"
44 #include "clang/Sema/ScopeInfo.h"
45 #include "clang/Sema/SemaCUDA.h"
47 #include "clang/Sema/SemaOpenMP.h"
48 #include "clang/Sema/SemaSYCL.h"
49 #include "clang/Sema/Template.h"
50 #include "llvm/ADT/ArrayRef.h"
51 #include "llvm/ADT/STLExtras.h"
52 #include "llvm/ADT/STLForwardCompat.h"
53 #include "llvm/ADT/ScopeExit.h"
54 #include "llvm/ADT/SmallString.h"
55 #include "llvm/ADT/StringExtras.h"
56 #include "llvm/Support/ConvertUTF.h"
57 #include "llvm/Support/SaveAndRestore.h"
58 #include <map>
59 #include <optional>
60 #include <set>
61 
62 using namespace clang;
63 
64 //===----------------------------------------------------------------------===//
65 // CheckDefaultArgumentVisitor
66 //===----------------------------------------------------------------------===//
67 
68 namespace {
69 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
70 /// the default argument of a parameter to determine whether it
71 /// contains any ill-formed subexpressions. For example, this will
72 /// diagnose the use of local variables or parameters within the
73 /// default argument expression.
74 class CheckDefaultArgumentVisitor
75  : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
76  Sema &S;
77  const Expr *DefaultArg;
78 
79 public:
80  CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
81  : S(S), DefaultArg(DefaultArg) {}
82 
83  bool VisitExpr(const Expr *Node);
84  bool VisitDeclRefExpr(const DeclRefExpr *DRE);
85  bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
86  bool VisitLambdaExpr(const LambdaExpr *Lambda);
87  bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
88 };
89 
90 /// VisitExpr - Visit all of the children of this expression.
91 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
92  bool IsInvalid = false;
93  for (const Stmt *SubStmt : Node->children())
94  if (SubStmt)
95  IsInvalid |= Visit(SubStmt);
96  return IsInvalid;
97 }
98 
99 /// VisitDeclRefExpr - Visit a reference to a declaration, to
100 /// determine whether this declaration can be used in the default
101 /// argument expression.
102 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
103  const ValueDecl *Decl = dyn_cast<ValueDecl>(DRE->getDecl());
104 
105  if (!isa<VarDecl, BindingDecl>(Decl))
106  return false;
107 
108  if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
109  // C++ [dcl.fct.default]p9:
110  // [...] parameters of a function shall not be used in default
111  // argument expressions, even if they are not evaluated. [...]
112  //
113  // C++17 [dcl.fct.default]p9 (by CWG 2082):
114  // [...] A parameter shall not appear as a potentially-evaluated
115  // expression in a default argument. [...]
116  //
117  if (DRE->isNonOdrUse() != NOUR_Unevaluated)
118  return S.Diag(DRE->getBeginLoc(),
119  diag::err_param_default_argument_references_param)
120  << Param->getDeclName() << DefaultArg->getSourceRange();
121  } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
122  // C++ [dcl.fct.default]p7:
123  // Local variables shall not be used in default argument
124  // expressions.
125  //
126  // C++17 [dcl.fct.default]p7 (by CWG 2082):
127  // A local variable shall not appear as a potentially-evaluated
128  // expression in a default argument.
129  //
130  // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
131  // Note: A local variable cannot be odr-used (6.3) in a default
132  // argument.
133  //
134  if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
135  return S.Diag(DRE->getBeginLoc(),
136  diag::err_param_default_argument_references_local)
137  << Decl << DefaultArg->getSourceRange();
138  }
139  return false;
140 }
141 
142 /// VisitCXXThisExpr - Visit a C++ "this" expression.
143 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
144  // C++ [dcl.fct.default]p8:
145  // The keyword this shall not be used in a default argument of a
146  // member function.
147  return S.Diag(ThisE->getBeginLoc(),
148  diag::err_param_default_argument_references_this)
149  << ThisE->getSourceRange();
150 }
151 
152 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
153  const PseudoObjectExpr *POE) {
154  bool Invalid = false;
155  for (const Expr *E : POE->semantics()) {
156  // Look through bindings.
157  if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
158  E = OVE->getSourceExpr();
159  assert(E && "pseudo-object binding without source expression?");
160  }
161 
162  Invalid |= Visit(E);
163  }
164  return Invalid;
165 }
166 
167 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
168  // [expr.prim.lambda.capture]p9
169  // a lambda-expression appearing in a default argument cannot implicitly or
170  // explicitly capture any local entity. Such a lambda-expression can still
171  // have an init-capture if any full-expression in its initializer satisfies
172  // the constraints of an expression appearing in a default argument.
173  bool Invalid = false;
174  for (const LambdaCapture &LC : Lambda->captures()) {
175  if (!Lambda->isInitCapture(&LC))
176  return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);
177  // Init captures are always VarDecl.
178  auto *D = cast<VarDecl>(LC.getCapturedVar());
179  Invalid |= Visit(D->getInit());
180  }
181  return Invalid;
182 }
183 } // namespace
184 
185 void
187  const CXXMethodDecl *Method) {
188  // If we have an MSAny spec already, don't bother.
189  if (!Method || ComputedEST == EST_MSAny)
190  return;
191 
192  const FunctionProtoType *Proto
193  = Method->getType()->getAs<FunctionProtoType>();
194  Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
195  if (!Proto)
196  return;
197 
199 
200  // If we have a throw-all spec at this point, ignore the function.
201  if (ComputedEST == EST_None)
202  return;
203 
204  if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
205  EST = EST_BasicNoexcept;
206 
207  switch (EST) {
208  case EST_Unparsed:
209  case EST_Uninstantiated:
210  case EST_Unevaluated:
211  llvm_unreachable("should not see unresolved exception specs here");
212 
213  // If this function can throw any exceptions, make a note of that.
214  case EST_MSAny:
215  case EST_None:
216  // FIXME: Whichever we see last of MSAny and None determines our result.
217  // We should make a consistent, order-independent choice here.
218  ClearExceptions();
219  ComputedEST = EST;
220  return;
221  case EST_NoexceptFalse:
222  ClearExceptions();
223  ComputedEST = EST_None;
224  return;
225  // FIXME: If the call to this decl is using any of its default arguments, we
226  // need to search them for potentially-throwing calls.
227  // If this function has a basic noexcept, it doesn't affect the outcome.
228  case EST_BasicNoexcept:
229  case EST_NoexceptTrue:
230  case EST_NoThrow:
231  return;
232  // If we're still at noexcept(true) and there's a throw() callee,
233  // change to that specification.
234  case EST_DynamicNone:
235  if (ComputedEST == EST_BasicNoexcept)
236  ComputedEST = EST_DynamicNone;
237  return;
239  llvm_unreachable(
240  "should not generate implicit declarations for dependent cases");
241  case EST_Dynamic:
242  break;
243  }
244  assert(EST == EST_Dynamic && "EST case not considered earlier.");
245  assert(ComputedEST != EST_None &&
246  "Shouldn't collect exceptions when throw-all is guaranteed.");
247  ComputedEST = EST_Dynamic;
248  // Record the exceptions in this function's exception specification.
249  for (const auto &E : Proto->exceptions())
250  if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
251  Exceptions.push_back(E);
252 }
253 
255  if (!S || ComputedEST == EST_MSAny)
256  return;
257 
258  // FIXME:
259  //
260  // C++0x [except.spec]p14:
261  // [An] implicit exception-specification specifies the type-id T if and
262  // only if T is allowed by the exception-specification of a function directly
263  // invoked by f's implicit definition; f shall allow all exceptions if any
264  // function it directly invokes allows all exceptions, and f shall allow no
265  // exceptions if every function it directly invokes allows no exceptions.
266  //
267  // Note in particular that if an implicit exception-specification is generated
268  // for a function containing a throw-expression, that specification can still
269  // be noexcept(true).
270  //
271  // Note also that 'directly invoked' is not defined in the standard, and there
272  // is no indication that we should only consider potentially-evaluated calls.
273  //
274  // Ultimately we should implement the intent of the standard: the exception
275  // specification should be the set of exceptions which can be thrown by the
276  // implicit definition. For now, we assume that any non-nothrow expression can
277  // throw any exception.
278 
279  if (Self->canThrow(S))
280  ComputedEST = EST_None;
281 }
282 
284  SourceLocation EqualLoc) {
285  if (RequireCompleteType(Param->getLocation(), Param->getType(),
286  diag::err_typecheck_decl_incomplete_type))
287  return true;
288 
289  // C++ [dcl.fct.default]p5
290  // A default argument expression is implicitly converted (clause
291  // 4) to the parameter type. The default argument expression has
292  // the same semantic constraints as the initializer expression in
293  // a declaration of a variable of the parameter type, using the
294  // copy-initialization semantics (8.5).
296  Param);
298  EqualLoc);
299  InitializationSequence InitSeq(*this, Entity, Kind, Arg);
300  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
301  if (Result.isInvalid())
302  return true;
303  Arg = Result.getAs<Expr>();
304 
305  CheckCompletedExpr(Arg, EqualLoc);
306  Arg = MaybeCreateExprWithCleanups(Arg);
307 
308  return Arg;
309 }
310 
312  SourceLocation EqualLoc) {
313  // Add the default argument to the parameter
314  Param->setDefaultArg(Arg);
315 
316  // We have already instantiated this parameter; provide each of the
317  // instantiations with the uninstantiated default argument.
318  UnparsedDefaultArgInstantiationsMap::iterator InstPos
319  = UnparsedDefaultArgInstantiations.find(Param);
320  if (InstPos != UnparsedDefaultArgInstantiations.end()) {
321  for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
322  InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
323 
324  // We're done tracking this parameter's instantiations.
325  UnparsedDefaultArgInstantiations.erase(InstPos);
326  }
327 }
328 
329 /// ActOnParamDefaultArgument - Check whether the default argument
330 /// provided for a function parameter is well-formed. If so, attach it
331 /// to the parameter declaration.
332 void
334  Expr *DefaultArg) {
335  if (!param || !DefaultArg)
336  return;
337 
338  ParmVarDecl *Param = cast<ParmVarDecl>(param);
339  UnparsedDefaultArgLocs.erase(Param);
340 
341  // Default arguments are only permitted in C++
342  if (!getLangOpts().CPlusPlus) {
343  Diag(EqualLoc, diag::err_param_default_argument)
344  << DefaultArg->getSourceRange();
345  return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
346  }
347 
348  // Check for unexpanded parameter packs.
350  return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
351 
352  // C++11 [dcl.fct.default]p3
353  // A default argument expression [...] shall not be specified for a
354  // parameter pack.
355  if (Param->isParameterPack()) {
356  Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
357  << DefaultArg->getSourceRange();
358  // Recover by discarding the default argument.
359  Param->setDefaultArg(nullptr);
360  return;
361  }
362 
363  ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
364  if (Result.isInvalid())
365  return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
366 
367  DefaultArg = Result.getAs<Expr>();
368 
369  // Check that the default argument is well-formed
370  CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
371  if (DefaultArgChecker.Visit(DefaultArg))
372  return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
373 
374  SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
375 }
376 
377 /// ActOnParamUnparsedDefaultArgument - We've seen a default
378 /// argument for a function parameter, but we can't parse it yet
379 /// because we're inside a class definition. Note that this default
380 /// argument will be parsed later.
382  SourceLocation EqualLoc,
383  SourceLocation ArgLoc) {
384  if (!param)
385  return;
386 
387  ParmVarDecl *Param = cast<ParmVarDecl>(param);
388  Param->setUnparsedDefaultArg();
389  UnparsedDefaultArgLocs[Param] = ArgLoc;
390 }
391 
392 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
393 /// the default argument for the parameter param failed.
395  Expr *DefaultArg) {
396  if (!param)
397  return;
398 
399  ParmVarDecl *Param = cast<ParmVarDecl>(param);
400  Param->setInvalidDecl();
401  UnparsedDefaultArgLocs.erase(Param);
402  ExprResult RE;
403  if (DefaultArg) {
404  RE = CreateRecoveryExpr(EqualLoc, DefaultArg->getEndLoc(), {DefaultArg},
405  Param->getType().getNonReferenceType());
406  } else {
407  RE = CreateRecoveryExpr(EqualLoc, EqualLoc, {},
408  Param->getType().getNonReferenceType());
409  }
410  Param->setDefaultArg(RE.get());
411 }
412 
413 /// CheckExtraCXXDefaultArguments - Check for any extra default
414 /// arguments in the declarator, which is not a function declaration
415 /// or definition and therefore is not permitted to have default
416 /// arguments. This routine should be invoked for every declarator
417 /// that is not a function declaration or definition.
419  // C++ [dcl.fct.default]p3
420  // A default argument expression shall be specified only in the
421  // parameter-declaration-clause of a function declaration or in a
422  // template-parameter (14.1). It shall not be specified for a
423  // parameter pack. If it is specified in a
424  // parameter-declaration-clause, it shall not occur within a
425  // declarator or abstract-declarator of a parameter-declaration.
426  bool MightBeFunction = D.isFunctionDeclarationContext();
427  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
428  DeclaratorChunk &chunk = D.getTypeObject(i);
429  if (chunk.Kind == DeclaratorChunk::Function) {
430  if (MightBeFunction) {
431  // This is a function declaration. It can have default arguments, but
432  // keep looking in case its return type is a function type with default
433  // arguments.
434  MightBeFunction = false;
435  continue;
436  }
437  for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
438  ++argIdx) {
439  ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
440  if (Param->hasUnparsedDefaultArg()) {
441  std::unique_ptr<CachedTokens> Toks =
442  std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
443  SourceRange SR;
444  if (Toks->size() > 1)
445  SR = SourceRange((*Toks)[1].getLocation(),
446  Toks->back().getLocation());
447  else
448  SR = UnparsedDefaultArgLocs[Param];
449  Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
450  << SR;
451  } else if (Param->getDefaultArg()) {
452  Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
453  << Param->getDefaultArg()->getSourceRange();
454  Param->setDefaultArg(nullptr);
455  }
456  }
457  } else if (chunk.Kind != DeclaratorChunk::Paren) {
458  MightBeFunction = false;
459  }
460  }
461 }
462 
464  return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
465  return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
466  });
467 }
468 
469 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
470 /// function, once we already know that they have the same
471 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
472 /// error, false otherwise.
474  Scope *S) {
475  bool Invalid = false;
476 
477  // The declaration context corresponding to the scope is the semantic
478  // parent, unless this is a local function declaration, in which case
479  // it is that surrounding function.
480  DeclContext *ScopeDC = New->isLocalExternDecl()
481  ? New->getLexicalDeclContext()
482  : New->getDeclContext();
483 
484  // Find the previous declaration for the purpose of default arguments.
485  FunctionDecl *PrevForDefaultArgs = Old;
486  for (/**/; PrevForDefaultArgs;
487  // Don't bother looking back past the latest decl if this is a local
488  // extern declaration; nothing else could work.
489  PrevForDefaultArgs = New->isLocalExternDecl()
490  ? nullptr
491  : PrevForDefaultArgs->getPreviousDecl()) {
492  // Ignore hidden declarations.
493  if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
494  continue;
495 
496  if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
497  !New->isCXXClassMember()) {
498  // Ignore default arguments of old decl if they are not in
499  // the same scope and this is not an out-of-line definition of
500  // a member function.
501  continue;
502  }
503 
504  if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
505  // If only one of these is a local function declaration, then they are
506  // declared in different scopes, even though isDeclInScope may think
507  // they're in the same scope. (If both are local, the scope check is
508  // sufficient, and if neither is local, then they are in the same scope.)
509  continue;
510  }
511 
512  // We found the right previous declaration.
513  break;
514  }
515 
516  // C++ [dcl.fct.default]p4:
517  // For non-template functions, default arguments can be added in
518  // later declarations of a function in the same
519  // scope. Declarations in different scopes have completely
520  // distinct sets of default arguments. That is, declarations in
521  // inner scopes do not acquire default arguments from
522  // declarations in outer scopes, and vice versa. In a given
523  // function declaration, all parameters subsequent to a
524  // parameter with a default argument shall have default
525  // arguments supplied in this or previous declarations. A
526  // default argument shall not be redefined by a later
527  // declaration (not even to the same value).
528  //
529  // C++ [dcl.fct.default]p6:
530  // Except for member functions of class templates, the default arguments
531  // in a member function definition that appears outside of the class
532  // definition are added to the set of default arguments provided by the
533  // member function declaration in the class definition.
534  for (unsigned p = 0, NumParams = PrevForDefaultArgs
535  ? PrevForDefaultArgs->getNumParams()
536  : 0;
537  p < NumParams; ++p) {
538  ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
539  ParmVarDecl *NewParam = New->getParamDecl(p);
540 
541  bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
542  bool NewParamHasDfl = NewParam->hasDefaultArg();
543 
544  if (OldParamHasDfl && NewParamHasDfl) {
545  unsigned DiagDefaultParamID =
546  diag::err_param_default_argument_redefinition;
547 
548  // MSVC accepts that default parameters be redefined for member functions
549  // of template class. The new default parameter's value is ignored.
550  Invalid = true;
551  if (getLangOpts().MicrosoftExt) {
552  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
553  if (MD && MD->getParent()->getDescribedClassTemplate()) {
554  // Merge the old default argument into the new parameter.
555  NewParam->setHasInheritedDefaultArg();
556  if (OldParam->hasUninstantiatedDefaultArg())
557  NewParam->setUninstantiatedDefaultArg(
558  OldParam->getUninstantiatedDefaultArg());
559  else
560  NewParam->setDefaultArg(OldParam->getInit());
561  DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
562  Invalid = false;
563  }
564  }
565 
566  // FIXME: If we knew where the '=' was, we could easily provide a fix-it
567  // hint here. Alternatively, we could walk the type-source information
568  // for NewParam to find the last source location in the type... but it
569  // isn't worth the effort right now. This is the kind of test case that
570  // is hard to get right:
571  // int f(int);
572  // void g(int (*fp)(int) = f);
573  // void g(int (*fp)(int) = &f);
574  Diag(NewParam->getLocation(), DiagDefaultParamID)
575  << NewParam->getDefaultArgRange();
576 
577  // Look for the function declaration where the default argument was
578  // actually written, which may be a declaration prior to Old.
579  for (auto Older = PrevForDefaultArgs;
580  OldParam->hasInheritedDefaultArg(); /**/) {
581  Older = Older->getPreviousDecl();
582  OldParam = Older->getParamDecl(p);
583  }
584 
585  Diag(OldParam->getLocation(), diag::note_previous_definition)
586  << OldParam->getDefaultArgRange();
587  } else if (OldParamHasDfl) {
588  // Merge the old default argument into the new parameter unless the new
589  // function is a friend declaration in a template class. In the latter
590  // case the default arguments will be inherited when the friend
591  // declaration will be instantiated.
592  if (New->getFriendObjectKind() == Decl::FOK_None ||
594  // It's important to use getInit() here; getDefaultArg()
595  // strips off any top-level ExprWithCleanups.
596  NewParam->setHasInheritedDefaultArg();
597  if (OldParam->hasUnparsedDefaultArg())
598  NewParam->setUnparsedDefaultArg();
599  else if (OldParam->hasUninstantiatedDefaultArg())
600  NewParam->setUninstantiatedDefaultArg(
601  OldParam->getUninstantiatedDefaultArg());
602  else
603  NewParam->setDefaultArg(OldParam->getInit());
604  }
605  } else if (NewParamHasDfl) {
606  if (New->getDescribedFunctionTemplate()) {
607  // Paragraph 4, quoted above, only applies to non-template functions.
608  Diag(NewParam->getLocation(),
609  diag::err_param_default_argument_template_redecl)
610  << NewParam->getDefaultArgRange();
611  Diag(PrevForDefaultArgs->getLocation(),
612  diag::note_template_prev_declaration)
613  << false;
614  } else if (New->getTemplateSpecializationKind()
617  // C++ [temp.expr.spec]p21:
618  // Default function arguments shall not be specified in a declaration
619  // or a definition for one of the following explicit specializations:
620  // - the explicit specialization of a function template;
621  // - the explicit specialization of a member function template;
622  // - the explicit specialization of a member function of a class
623  // template where the class template specialization to which the
624  // member function specialization belongs is implicitly
625  // instantiated.
626  Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
628  << New->getDeclName()
629  << NewParam->getDefaultArgRange();
630  } else if (New->getDeclContext()->isDependentContext()) {
631  // C++ [dcl.fct.default]p6 (DR217):
632  // Default arguments for a member function of a class template shall
633  // be specified on the initial declaration of the member function
634  // within the class template.
635  //
636  // Reading the tea leaves a bit in DR217 and its reference to DR205
637  // leads me to the conclusion that one cannot add default function
638  // arguments for an out-of-line definition of a member function of a
639  // dependent type.
640  int WhichKind = 2;
641  if (CXXRecordDecl *Record
642  = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
643  if (Record->getDescribedClassTemplate())
644  WhichKind = 0;
645  else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
646  WhichKind = 1;
647  else
648  WhichKind = 2;
649  }
650 
651  Diag(NewParam->getLocation(),
652  diag::err_param_default_argument_member_template_redecl)
653  << WhichKind
654  << NewParam->getDefaultArgRange();
655  }
656  }
657  }
658 
659  // DR1344: If a default argument is added outside a class definition and that
660  // default argument makes the function a special member function, the program
661  // is ill-formed. This can only happen for constructors.
662  if (isa<CXXConstructorDecl>(New) &&
664  CXXSpecialMemberKind NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
665  OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
666  if (NewSM != OldSM) {
667  ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
668  assert(NewParam->hasDefaultArg());
669  Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
670  << NewParam->getDefaultArgRange() << llvm::to_underlying(NewSM);
671  Diag(Old->getLocation(), diag::note_previous_declaration);
672  }
673  }
674 
675  const FunctionDecl *Def;
676  // C++11 [dcl.constexpr]p1: If any declaration of a function or function
677  // template has a constexpr specifier then all its declarations shall
678  // contain the constexpr specifier.
679  if (New->getConstexprKind() != Old->getConstexprKind()) {
680  Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
681  << New << static_cast<int>(New->getConstexprKind())
682  << static_cast<int>(Old->getConstexprKind());
683  Diag(Old->getLocation(), diag::note_previous_declaration);
684  Invalid = true;
685  } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
686  Old->isDefined(Def) &&
687  // If a friend function is inlined but does not have 'inline'
688  // specifier, it is a definition. Do not report attribute conflict
689  // in this case, redefinition will be diagnosed later.
690  (New->isInlineSpecified() ||
691  New->getFriendObjectKind() == Decl::FOK_None)) {
692  // C++11 [dcl.fcn.spec]p4:
693  // If the definition of a function appears in a translation unit before its
694  // first declaration as inline, the program is ill-formed.
695  Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
696  Diag(Def->getLocation(), diag::note_previous_definition);
697  Invalid = true;
698  }
699 
700  // C++17 [temp.deduct.guide]p3:
701  // Two deduction guide declarations in the same translation unit
702  // for the same class template shall not have equivalent
703  // parameter-declaration-clauses.
704  if (isa<CXXDeductionGuideDecl>(New) &&
706  Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
707  Diag(Old->getLocation(), diag::note_previous_declaration);
708  }
709 
710  // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
711  // argument expression, that declaration shall be a definition and shall be
712  // the only declaration of the function or function template in the
713  // translation unit.
716  Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
717  Diag(Old->getLocation(), diag::note_previous_declaration);
718  Invalid = true;
719  }
720 
721  // C++11 [temp.friend]p4 (DR329):
722  // When a function is defined in a friend function declaration in a class
723  // template, the function is instantiated when the function is odr-used.
724  // The same restrictions on multiple declarations and definitions that
725  // apply to non-template function declarations and definitions also apply
726  // to these implicit definitions.
727  const FunctionDecl *OldDefinition = nullptr;
729  Old->isDefined(OldDefinition, true))
730  CheckForFunctionRedefinition(New, OldDefinition);
731 
732  return Invalid;
733 }
734 
737  ? diag::warn_cxx23_placeholder_var_definition
738  : diag::ext_placeholder_var_definition);
739 }
740 
741 NamedDecl *
743  MultiTemplateParamsArg TemplateParamLists) {
744  assert(D.isDecompositionDeclarator());
746 
747  // The syntax only allows a decomposition declarator as a simple-declaration,
748  // a for-range-declaration, or a condition in Clang, but we parse it in more
749  // cases than that.
751  Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
752  << Decomp.getSourceRange();
753  return nullptr;
754  }
755 
756  if (!TemplateParamLists.empty()) {
757  // FIXME: There's no rule against this, but there are also no rules that
758  // would actually make it usable, so we reject it for now.
759  Diag(TemplateParamLists.front()->getTemplateLoc(),
760  diag::err_decomp_decl_template);
761  return nullptr;
762  }
763 
764  Diag(Decomp.getLSquareLoc(),
766  ? diag::ext_decomp_decl
768  ? diag::ext_decomp_decl_cond
769  : diag::warn_cxx14_compat_decomp_decl)
770  << Decomp.getSourceRange();
771 
772  // The semantic context is always just the current context.
773  DeclContext *const DC = CurContext;
774 
775  // C++17 [dcl.dcl]/8:
776  // The decl-specifier-seq shall contain only the type-specifier auto
777  // and cv-qualifiers.
778  // C++20 [dcl.dcl]/8:
779  // If decl-specifier-seq contains any decl-specifier other than static,
780  // thread_local, auto, or cv-qualifiers, the program is ill-formed.
781  // C++23 [dcl.pre]/6:
782  // Each decl-specifier in the decl-specifier-seq shall be static,
783  // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
784  auto &DS = D.getDeclSpec();
785  {
786  // Note: While constrained-auto needs to be checked, we do so separately so
787  // we can emit a better diagnostic.
788  SmallVector<StringRef, 8> BadSpecifiers;
789  SmallVector<SourceLocation, 8> BadSpecifierLocs;
790  SmallVector<StringRef, 8> CPlusPlus20Specifiers;
791  SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
792  if (auto SCS = DS.getStorageClassSpec()) {
793  if (SCS == DeclSpec::SCS_static) {
794  CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
795  CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
796  } else {
797  BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
798  BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
799  }
800  }
801  if (auto TSCS = DS.getThreadStorageClassSpec()) {
802  CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
803  CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
804  }
805  if (DS.hasConstexprSpecifier()) {
806  BadSpecifiers.push_back(
807  DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
808  BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
809  }
810  if (DS.isInlineSpecified()) {
811  BadSpecifiers.push_back("inline");
812  BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
813  }
814 
815  if (!BadSpecifiers.empty()) {
816  auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
817  Err << (int)BadSpecifiers.size()
818  << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
819  // Don't add FixItHints to remove the specifiers; we do still respect
820  // them when building the underlying variable.
821  for (auto Loc : BadSpecifierLocs)
822  Err << SourceRange(Loc, Loc);
823  } else if (!CPlusPlus20Specifiers.empty()) {
824  auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
826  ? diag::warn_cxx17_compat_decomp_decl_spec
827  : diag::ext_decomp_decl_spec);
828  Warn << (int)CPlusPlus20Specifiers.size()
829  << llvm::join(CPlusPlus20Specifiers.begin(),
830  CPlusPlus20Specifiers.end(), " ");
831  for (auto Loc : CPlusPlus20SpecifierLocs)
832  Warn << SourceRange(Loc, Loc);
833  }
834  // We can't recover from it being declared as a typedef.
835  if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
836  return nullptr;
837  }
838 
839  // C++2a [dcl.struct.bind]p1:
840  // A cv that includes volatile is deprecated
841  if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
843  Diag(DS.getVolatileSpecLoc(),
844  diag::warn_deprecated_volatile_structured_binding);
845 
847  QualType R = TInfo->getType();
848 
851  D.setInvalidType();
852 
853  // The syntax only allows a single ref-qualifier prior to the decomposition
854  // declarator. No other declarator chunks are permitted. Also check the type
855  // specifier here.
856  if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
857  D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
858  (D.getNumTypeObjects() == 1 &&
860  Diag(Decomp.getLSquareLoc(),
861  (D.hasGroupingParens() ||
862  (D.getNumTypeObjects() &&
864  ? diag::err_decomp_decl_parens
865  : diag::err_decomp_decl_type)
866  << R;
867 
868  // In most cases, there's no actual problem with an explicitly-specified
869  // type, but a function type won't work here, and ActOnVariableDeclarator
870  // shouldn't be called for such a type.
871  if (R->isFunctionType())
872  D.setInvalidType();
873  }
874 
875  // Constrained auto is prohibited by [decl.pre]p6, so check that here.
876  if (DS.isConstrainedAuto()) {
877  TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
878  assert(TemplRep->Kind == TNK_Concept_template &&
879  "No other template kind should be possible for a constrained auto");
880 
881  SourceRange TemplRange{TemplRep->TemplateNameLoc,
882  TemplRep->RAngleLoc.isValid()
883  ? TemplRep->RAngleLoc
884  : TemplRep->TemplateNameLoc};
885  Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
886  << TemplRange << FixItHint::CreateRemoval(TemplRange);
887  }
888 
889  // Build the BindingDecls.
891 
892  // Build the BindingDecls.
893  for (auto &B : D.getDecompositionDeclarator().bindings()) {
894  // Check for name conflicts.
895  DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
896  IdentifierInfo *VarName = B.Name;
897  assert(VarName && "Cannot have an unnamed binding declaration");
898 
899  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
901  LookupName(Previous, S,
902  /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
903 
904  // It's not permitted to shadow a template parameter name.
905  if (Previous.isSingleResult() &&
906  Previous.getFoundDecl()->isTemplateParameter()) {
908  Previous.getFoundDecl());
909  Previous.clear();
910  }
911 
912  auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, VarName);
913 
914  // Find the shadowed declaration before filtering for scope.
915  NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
917  : nullptr;
918 
919  bool ConsiderLinkage = DC->isFunctionOrMethod() &&
920  DS.getStorageClassSpec() == DeclSpec::SCS_extern;
921  FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
922  /*AllowInlineNamespace*/false);
923 
924  bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
925  DC->isFunctionOrMethod() && VarName->isPlaceholder();
926  if (!Previous.empty()) {
927  if (IsPlaceholder) {
928  bool sameDC = (Previous.end() - 1)
929  ->getDeclContext()
930  ->getRedeclContext()
931  ->Equals(DC->getRedeclContext());
932  if (sameDC &&
933  isDeclInScope(*(Previous.end() - 1), CurContext, S, false)) {
934  Previous.clear();
936  }
937  } else {
938  auto *Old = Previous.getRepresentativeDecl();
939  Diag(B.NameLoc, diag::err_redefinition) << B.Name;
940  Diag(Old->getLocation(), diag::note_previous_definition);
941  }
942  } else if (ShadowedDecl && !D.isRedeclaration()) {
943  CheckShadow(BD, ShadowedDecl, Previous);
944  }
945  PushOnScopeChains(BD, S, true);
946  Bindings.push_back(BD);
947  ParsingInitForAutoVars.insert(BD);
948  }
949 
950  // There are no prior lookup results for the variable itself, because it
951  // is unnamed.
952  DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
953  Decomp.getLSquareLoc());
954  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
956 
957  // Build the variable that holds the non-decomposed object.
958  bool AddToScope = true;
959  NamedDecl *New =
960  ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
961  MultiTemplateParamsArg(), AddToScope, Bindings);
962  if (AddToScope) {
963  S->AddDecl(New);
965  }
966 
967  if (OpenMP().isInOpenMPDeclareTargetContext())
969 
970  return New;
971 }
972 
975  QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
976  llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
977  if ((int64_t)Bindings.size() != NumElems) {
978  S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
979  << DecompType << (unsigned)Bindings.size()
980  << (unsigned)NumElems.getLimitedValue(UINT_MAX)
981  << toString(NumElems, 10) << (NumElems < Bindings.size());
982  return true;
983  }
984 
985  unsigned I = 0;
986  for (auto *B : Bindings) {
987  SourceLocation Loc = B->getLocation();
988  ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
989  if (E.isInvalid())
990  return true;
991  E = GetInit(Loc, E.get(), I++);
992  if (E.isInvalid())
993  return true;
994  B->setBinding(ElemType, E.get());
995  }
996 
997  return false;
998 }
999 
1002  ValueDecl *Src, QualType DecompType,
1003  const llvm::APSInt &NumElems,
1004  QualType ElemType) {
1005  return checkSimpleDecomposition(
1006  S, Bindings, Src, DecompType, NumElems, ElemType,
1007  [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1008  ExprResult E = S.ActOnIntegerConstant(Loc, I);
1009  if (E.isInvalid())
1010  return ExprError();
1011  return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
1012  });
1013 }
1014 
1016  ValueDecl *Src, QualType DecompType,
1017  const ConstantArrayType *CAT) {
1018  return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1019  llvm::APSInt(CAT->getSize()),
1020  CAT->getElementType());
1021 }
1022 
1024  ValueDecl *Src, QualType DecompType,
1025  const VectorType *VT) {
1027  S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
1029  DecompType.getQualifiers()));
1030 }
1031 
1034  ValueDecl *Src, QualType DecompType,
1035  const ComplexType *CT) {
1036  return checkSimpleDecomposition(
1037  S, Bindings, Src, DecompType, llvm::APSInt::get(2),
1039  DecompType.getQualifiers()),
1040  [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1041  return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
1042  });
1043 }
1044 
1047  const TemplateParameterList *Params) {
1048  SmallString<128> SS;
1049  llvm::raw_svector_ostream OS(SS);
1050  bool First = true;
1051  unsigned I = 0;
1052  for (auto &Arg : Args.arguments()) {
1053  if (!First)
1054  OS << ", ";
1055  Arg.getArgument().print(PrintingPolicy, OS,
1057  PrintingPolicy, Params, I));
1058  First = false;
1059  I++;
1060  }
1061  return std::string(OS.str());
1062 }
1063 
1064 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
1065  SourceLocation Loc, StringRef Trait,
1067  unsigned DiagID) {
1068  auto DiagnoseMissing = [&] {
1069  if (DiagID)
1070  S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1071  Args, /*Params*/ nullptr);
1072  return true;
1073  };
1074 
1075  // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1077  if (!Std)
1078  return DiagnoseMissing();
1079 
1080  // Look up the trait itself, within namespace std. We can diagnose various
1081  // problems with this lookup even if we've been asked to not diagnose a
1082  // missing specialization, because this can only fail if the user has been
1083  // declaring their own names in namespace std or we don't support the
1084  // standard library implementation in use.
1085  LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
1087  if (!S.LookupQualifiedName(Result, Std))
1088  return DiagnoseMissing();
1089  if (Result.isAmbiguous())
1090  return true;
1091 
1092  ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1093  if (!TraitTD) {
1094  Result.suppressDiagnostics();
1095  NamedDecl *Found = *Result.begin();
1096  S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1097  S.Diag(Found->getLocation(), diag::note_declared_at);
1098  return true;
1099  }
1100 
1101  // Build the template-id.
1102  QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1103  if (TraitTy.isNull())
1104  return true;
1105  if (!S.isCompleteType(Loc, TraitTy)) {
1106  if (DiagID)
1108  Loc, TraitTy, DiagID,
1110  TraitTD->getTemplateParameters()));
1111  return true;
1112  }
1113 
1114  CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1115  assert(RD && "specialization of class template is not a class?");
1116 
1117  // Look up the member of the trait type.
1118  S.LookupQualifiedName(TraitMemberLookup, RD);
1119  return TraitMemberLookup.isAmbiguous();
1120 }
1121 
1122 static TemplateArgumentLoc
1124  uint64_t I) {
1126  return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1127 }
1128 
1129 static TemplateArgumentLoc
1132 }
1133 
1134 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1135 
1136 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1137  llvm::APSInt &Size) {
1140 
1143 
1144  // Form template argument list for tuple_size<T>.
1145  TemplateArgumentListInfo Args(Loc, Loc);
1147 
1148  // If there's no tuple_size specialization or the lookup of 'value' is empty,
1149  // it's not tuple-like.
1150  if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1151  R.empty())
1152  return IsTupleLike::NotTupleLike;
1153 
1154  // If we get this far, we've committed to the tuple interpretation, but
1155  // we can still fail if there actually isn't a usable ::value.
1156 
1157  struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1158  LookupResult &R;
1160  ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1161  : R(R), Args(Args) {}
1162  Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1163  SourceLocation Loc) override {
1164  return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1166  /*Params*/ nullptr);
1167  }
1168  } Diagnoser(R, Args);
1169 
1170  ExprResult E =
1171  S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1172  if (E.isInvalid())
1173  return IsTupleLike::Error;
1174 
1175  E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1176  if (E.isInvalid())
1177  return IsTupleLike::Error;
1178 
1179  return IsTupleLike::TupleLike;
1180 }
1181 
1182 /// \return std::tuple_element<I, T>::type.
1184  unsigned I, QualType T) {
1185  // Form template argument list for tuple_element<I, T>.
1186  TemplateArgumentListInfo Args(Loc, Loc);
1187  Args.addArgument(
1190 
1191  DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1192  LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1194  S, R, Loc, "tuple_element", Args,
1195  diag::err_decomp_decl_std_tuple_element_not_specialized))
1196  return QualType();
1197 
1198  auto *TD = R.getAsSingle<TypeDecl>();
1199  if (!TD) {
1200  R.suppressDiagnostics();
1201  S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1203  /*Params*/ nullptr);
1204  if (!R.empty())
1205  S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1206  return QualType();
1207  }
1208 
1209  return S.Context.getTypeDeclType(TD);
1210 }
1211 
1212 namespace {
1213 struct InitializingBinding {
1214  Sema &S;
1215  InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1218  Ctx.PointOfInstantiation = BD->getLocation();
1219  Ctx.Entity = BD;
1220  S.pushCodeSynthesisContext(Ctx);
1221  }
1222  ~InitializingBinding() {
1224  }
1225 };
1226 }
1227 
1230  VarDecl *Src, QualType DecompType,
1231  const llvm::APSInt &TupleSize) {
1232  if ((int64_t)Bindings.size() != TupleSize) {
1233  S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1234  << DecompType << (unsigned)Bindings.size()
1235  << (unsigned)TupleSize.getLimitedValue(UINT_MAX)
1236  << toString(TupleSize, 10) << (TupleSize < Bindings.size());
1237  return true;
1238  }
1239 
1240  if (Bindings.empty())
1241  return false;
1242 
1243  DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1244 
1245  // [dcl.decomp]p3:
1246  // The unqualified-id get is looked up in the scope of E by class member
1247  // access lookup ...
1248  LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1249  bool UseMemberGet = false;
1250  if (S.isCompleteType(Src->getLocation(), DecompType)) {
1251  if (auto *RD = DecompType->getAsCXXRecordDecl())
1252  S.LookupQualifiedName(MemberGet, RD);
1253  if (MemberGet.isAmbiguous())
1254  return true;
1255  // ... and if that finds at least one declaration that is a function
1256  // template whose first template parameter is a non-type parameter ...
1257  for (NamedDecl *D : MemberGet) {
1258  if (FunctionTemplateDecl *FTD =
1259  dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1260  TemplateParameterList *TPL = FTD->getTemplateParameters();
1261  if (TPL->size() != 0 &&
1262  isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1263  // ... the initializer is e.get<i>().
1264  UseMemberGet = true;
1265  break;
1266  }
1267  }
1268  }
1269  }
1270 
1271  unsigned I = 0;
1272  for (auto *B : Bindings) {
1273  InitializingBinding InitContext(S, B);
1274  SourceLocation Loc = B->getLocation();
1275 
1276  ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1277  if (E.isInvalid())
1278  return true;
1279 
1280  // e is an lvalue if the type of the entity is an lvalue reference and
1281  // an xvalue otherwise
1282  if (!Src->getType()->isLValueReferenceType())
1283  E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1284  E.get(), nullptr, VK_XValue,
1285  FPOptionsOverride());
1286 
1287  TemplateArgumentListInfo Args(Loc, Loc);
1288  Args.addArgument(
1290 
1291  if (UseMemberGet) {
1292  // if [lookup of member get] finds at least one declaration, the
1293  // initializer is e.get<i-1>().
1294  E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1295  CXXScopeSpec(), SourceLocation(), nullptr,
1296  MemberGet, &Args, nullptr);
1297  if (E.isInvalid())
1298  return true;
1299 
1300  E = S.BuildCallExpr(nullptr, E.get(), Loc, std::nullopt, Loc);
1301  } else {
1302  // Otherwise, the initializer is get<i-1>(e), where get is looked up
1303  // in the associated namespaces.
1306  DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, &Args,
1308  /*KnownDependent=*/false);
1309 
1310  Expr *Arg = E.get();
1311  E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1312  }
1313  if (E.isInvalid())
1314  return true;
1315  Expr *Init = E.get();
1316 
1317  // Given the type T designated by std::tuple_element<i - 1, E>::type,
1318  QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1319  if (T.isNull())
1320  return true;
1321 
1322  // each vi is a variable of type "reference to T" initialized with the
1323  // initializer, where the reference is an lvalue reference if the
1324  // initializer is an lvalue and an rvalue reference otherwise
1325  QualType RefType =
1326  S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1327  if (RefType.isNull())
1328  return true;
1329  auto *RefVD = VarDecl::Create(
1330  S.Context, Src->getDeclContext(), Loc, Loc,
1331  B->getDeclName().getAsIdentifierInfo(), RefType,
1333  RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1334  RefVD->setTSCSpec(Src->getTSCSpec());
1335  RefVD->setImplicit();
1336  if (Src->isInlineSpecified())
1337  RefVD->setInlineSpecified();
1338  RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1339 
1342  InitializationSequence Seq(S, Entity, Kind, Init);
1343  E = Seq.Perform(S, Entity, Kind, Init);
1344  if (E.isInvalid())
1345  return true;
1346  E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1347  if (E.isInvalid())
1348  return true;
1349  RefVD->setInit(E.get());
1351 
1353  DeclarationNameInfo(B->getDeclName(), Loc),
1354  RefVD);
1355  if (E.isInvalid())
1356  return true;
1357 
1358  B->setBinding(T, E.get());
1359  I++;
1360  }
1361 
1362  return false;
1363 }
1364 
1365 /// Find the base class to decompose in a built-in decomposition of a class type.
1366 /// This base class search is, unfortunately, not quite like any other that we
1367 /// perform anywhere else in C++.
1369  const CXXRecordDecl *RD,
1370  CXXCastPath &BasePath) {
1371  auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1372  CXXBasePath &Path) {
1373  return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1374  };
1375 
1376  const CXXRecordDecl *ClassWithFields = nullptr;
1378  if (RD->hasDirectFields())
1379  // [dcl.decomp]p4:
1380  // Otherwise, all of E's non-static data members shall be public direct
1381  // members of E ...
1382  ClassWithFields = RD;
1383  else {
1384  // ... or of ...
1385  CXXBasePaths Paths;
1386  Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1387  if (!RD->lookupInBases(BaseHasFields, Paths)) {
1388  // If no classes have fields, just decompose RD itself. (This will work
1389  // if and only if zero bindings were provided.)
1390  return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1391  }
1392 
1393  CXXBasePath *BestPath = nullptr;
1394  for (auto &P : Paths) {
1395  if (!BestPath)
1396  BestPath = &P;
1397  else if (!S.Context.hasSameType(P.back().Base->getType(),
1398  BestPath->back().Base->getType())) {
1399  // ... the same ...
1400  S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1401  << false << RD << BestPath->back().Base->getType()
1402  << P.back().Base->getType();
1403  return DeclAccessPair();
1404  } else if (P.Access < BestPath->Access) {
1405  BestPath = &P;
1406  }
1407  }
1408 
1409  // ... unambiguous ...
1410  QualType BaseType = BestPath->back().Base->getType();
1411  if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1412  S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1413  << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1414  return DeclAccessPair();
1415  }
1416 
1417  // ... [accessible, implied by other rules] base class of E.
1418  S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1419  *BestPath, diag::err_decomp_decl_inaccessible_base);
1420  AS = BestPath->Access;
1421 
1422  ClassWithFields = BaseType->getAsCXXRecordDecl();
1423  S.BuildBasePathArray(Paths, BasePath);
1424  }
1425 
1426  // The above search did not check whether the selected class itself has base
1427  // classes with fields, so check that now.
1428  CXXBasePaths Paths;
1429  if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1430  S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1431  << (ClassWithFields == RD) << RD << ClassWithFields
1432  << Paths.front().back().Base->getType();
1433  return DeclAccessPair();
1434  }
1435 
1436  return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1437 }
1438 
1440  ValueDecl *Src, QualType DecompType,
1441  const CXXRecordDecl *OrigRD) {
1442  if (S.RequireCompleteType(Src->getLocation(), DecompType,
1443  diag::err_incomplete_type))
1444  return true;
1445 
1446  CXXCastPath BasePath;
1447  DeclAccessPair BasePair =
1448  findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1449  const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1450  if (!RD)
1451  return true;
1453  DecompType.getQualifiers());
1454 
1455  auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1456  unsigned NumFields = llvm::count_if(
1457  RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1458  assert(Bindings.size() != NumFields);
1459  S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1460  << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1461  << (NumFields < Bindings.size());
1462  return true;
1463  };
1464 
1465  // all of E's non-static data members shall be [...] well-formed
1466  // when named as e.name in the context of the structured binding,
1467  // E shall not have an anonymous union member, ...
1468  unsigned I = 0;
1469  for (auto *FD : RD->fields()) {
1470  if (FD->isUnnamedBitField())
1471  continue;
1472 
1473  // All the non-static data members are required to be nameable, so they
1474  // must all have names.
1475  if (!FD->getDeclName()) {
1476  if (RD->isLambda()) {
1477  S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1478  S.Diag(RD->getLocation(), diag::note_lambda_decl);
1479  return true;
1480  }
1481 
1482  if (FD->isAnonymousStructOrUnion()) {
1483  S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1484  << DecompType << FD->getType()->isUnionType();
1485  S.Diag(FD->getLocation(), diag::note_declared_at);
1486  return true;
1487  }
1488 
1489  // FIXME: Are there any other ways we could have an anonymous member?
1490  }
1491 
1492  // We have a real field to bind.
1493  if (I >= Bindings.size())
1494  return DiagnoseBadNumberOfBindings();
1495  auto *B = Bindings[I++];
1496  SourceLocation Loc = B->getLocation();
1497 
1498  // The field must be accessible in the context of the structured binding.
1499  // We already checked that the base class is accessible.
1500  // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1501  // const_cast here.
1503  Loc, const_cast<CXXRecordDecl *>(OrigRD),
1505  BasePair.getAccess(), FD->getAccess())));
1506 
1507  // Initialize the binding to Src.FD.
1508  ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1509  if (E.isInvalid())
1510  return true;
1511  E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1512  VK_LValue, &BasePath);
1513  if (E.isInvalid())
1514  return true;
1515  E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1516  CXXScopeSpec(), FD,
1517  DeclAccessPair::make(FD, FD->getAccess()),
1518  DeclarationNameInfo(FD->getDeclName(), Loc));
1519  if (E.isInvalid())
1520  return true;
1521 
1522  // If the type of the member is T, the referenced type is cv T, where cv is
1523  // the cv-qualification of the decomposition expression.
1524  //
1525  // FIXME: We resolve a defect here: if the field is mutable, we do not add
1526  // 'const' to the type of the field.
1527  Qualifiers Q = DecompType.getQualifiers();
1528  if (FD->isMutable())
1529  Q.removeConst();
1530  B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1531  }
1532 
1533  if (I != Bindings.size())
1534  return DiagnoseBadNumberOfBindings();
1535 
1536  return false;
1537 }
1538 
1540  QualType DecompType = DD->getType();
1541 
1542  // If the type of the decomposition is dependent, then so is the type of
1543  // each binding.
1544  if (DecompType->isDependentType()) {
1545  for (auto *B : DD->bindings())
1546  B->setType(Context.DependentTy);
1547  return;
1548  }
1549 
1550  DecompType = DecompType.getNonReferenceType();
1552 
1553  // C++1z [dcl.decomp]/2:
1554  // If E is an array type [...]
1555  // As an extension, we also support decomposition of built-in complex and
1556  // vector types.
1557  if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1558  if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1559  DD->setInvalidDecl();
1560  return;
1561  }
1562  if (auto *VT = DecompType->getAs<VectorType>()) {
1563  if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1564  DD->setInvalidDecl();
1565  return;
1566  }
1567  if (auto *CT = DecompType->getAs<ComplexType>()) {
1568  if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1569  DD->setInvalidDecl();
1570  return;
1571  }
1572 
1573  // C++1z [dcl.decomp]/3:
1574  // if the expression std::tuple_size<E>::value is a well-formed integral
1575  // constant expression, [...]
1576  llvm::APSInt TupleSize(32);
1577  switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1578  case IsTupleLike::Error:
1579  DD->setInvalidDecl();
1580  return;
1581 
1582  case IsTupleLike::TupleLike:
1583  if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1584  DD->setInvalidDecl();
1585  return;
1586 
1587  case IsTupleLike::NotTupleLike:
1588  break;
1589  }
1590 
1591  // C++1z [dcl.dcl]/8:
1592  // [E shall be of array or non-union class type]
1593  CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1594  if (!RD || RD->isUnion()) {
1595  Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1596  << DD << !RD << DecompType;
1597  DD->setInvalidDecl();
1598  return;
1599  }
1600 
1601  // C++1z [dcl.decomp]/4:
1602  // all of E's non-static data members shall be [...] direct members of
1603  // E or of the same unambiguous public base class of E, ...
1604  if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1605  DD->setInvalidDecl();
1606 }
1607 
1608 /// Merge the exception specifications of two variable declarations.
1609 ///
1610 /// This is called when there's a redeclaration of a VarDecl. The function
1611 /// checks if the redeclaration might have an exception specification and
1612 /// validates compatibility and merges the specs if necessary.
1614  // Shortcut if exceptions are disabled.
1615  if (!getLangOpts().CXXExceptions)
1616  return;
1617 
1618  assert(Context.hasSameType(New->getType(), Old->getType()) &&
1619  "Should only be called if types are otherwise the same.");
1620 
1621  QualType NewType = New->getType();
1622  QualType OldType = Old->getType();
1623 
1624  // We're only interested in pointers and references to functions, as well
1625  // as pointers to member functions.
1626  if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1627  NewType = R->getPointeeType();
1628  OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1629  } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1630  NewType = P->getPointeeType();
1631  OldType = OldType->castAs<PointerType>()->getPointeeType();
1632  } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1633  NewType = M->getPointeeType();
1634  OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1635  }
1636 
1637  if (!NewType->isFunctionProtoType())
1638  return;
1639 
1640  // There's lots of special cases for functions. For function pointers, system
1641  // libraries are hopefully not as broken so that we don't need these
1642  // workarounds.
1644  OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1645  NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1646  New->setInvalidDecl();
1647  }
1648 }
1649 
1650 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1651 /// function declaration are well-formed according to C++
1652 /// [dcl.fct.default].
1654  unsigned NumParams = FD->getNumParams();
1655  unsigned ParamIdx = 0;
1656 
1657  // This checking doesn't make sense for explicit specializations; their
1658  // default arguments are determined by the declaration we're specializing,
1659  // not by FD.
1661  return;
1662  if (auto *FTD = FD->getDescribedFunctionTemplate())
1663  if (FTD->isMemberSpecialization())
1664  return;
1665 
1666  // Find first parameter with a default argument
1667  for (; ParamIdx < NumParams; ++ParamIdx) {
1668  ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1669  if (Param->hasDefaultArg())
1670  break;
1671  }
1672 
1673  // C++20 [dcl.fct.default]p4:
1674  // In a given function declaration, each parameter subsequent to a parameter
1675  // with a default argument shall have a default argument supplied in this or
1676  // a previous declaration, unless the parameter was expanded from a
1677  // parameter pack, or shall be a function parameter pack.
1678  for (; ParamIdx < NumParams; ++ParamIdx) {
1679  ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1680  if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1683  if (Param->isInvalidDecl())
1684  /* We already complained about this parameter. */;
1685  else if (Param->getIdentifier())
1686  Diag(Param->getLocation(),
1687  diag::err_param_default_argument_missing_name)
1688  << Param->getIdentifier();
1689  else
1690  Diag(Param->getLocation(),
1691  diag::err_param_default_argument_missing);
1692  }
1693  }
1694 }
1695 
1696 /// Check that the given type is a literal type. Issue a diagnostic if not,
1697 /// if Kind is Diagnose.
1698 /// \return \c true if a problem has been found (and optionally diagnosed).
1699 template <typename... Ts>
1701  SourceLocation Loc, QualType T, unsigned DiagID,
1702  Ts &&...DiagArgs) {
1703  if (T->isDependentType())
1704  return false;
1705 
1706  switch (Kind) {
1708  return SemaRef.RequireLiteralType(Loc, T, DiagID,
1709  std::forward<Ts>(DiagArgs)...);
1710 
1712  return !T->isLiteralType(SemaRef.Context);
1713  }
1714 
1715  llvm_unreachable("unknown CheckConstexprKind");
1716 }
1717 
1718 /// Determine whether a destructor cannot be constexpr due to
1720  const CXXDestructorDecl *DD,
1722  assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1723  "this check is obsolete for C++23");
1724  auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1725  const CXXRecordDecl *RD =
1727  if (!RD || RD->hasConstexprDestructor())
1728  return true;
1729 
1731  SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1732  << static_cast<int>(DD->getConstexprKind()) << !FD
1733  << (FD ? FD->getDeclName() : DeclarationName()) << T;
1734  SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1735  << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1736  }
1737  return false;
1738  };
1739 
1740  const CXXRecordDecl *RD = DD->getParent();
1741  for (const CXXBaseSpecifier &B : RD->bases())
1742  if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1743  return false;
1744  for (const FieldDecl *FD : RD->fields())
1745  if (!Check(FD->getLocation(), FD->getType(), FD))
1746  return false;
1747  return true;
1748 }
1749 
1750 /// Check whether a function's parameter types are all literal types. If so,
1751 /// return true. If not, produce a suitable diagnostic and return false.
1753  const FunctionDecl *FD,
1755  assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1756  "this check is obsolete for C++23");
1757  unsigned ArgIndex = 0;
1758  const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1759  for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1760  e = FT->param_type_end();
1761  i != e; ++i, ++ArgIndex) {
1762  const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1763  assert(PD && "null in a parameter list");
1764  SourceLocation ParamLoc = PD->getLocation();
1765  if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1766  diag::err_constexpr_non_literal_param, ArgIndex + 1,
1767  PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1768  FD->isConsteval()))
1769  return false;
1770  }
1771  return true;
1772 }
1773 
1774 /// Check whether a function's return type is a literal type. If so, return
1775 /// true. If not, produce a suitable diagnostic and return false.
1778  assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1779  "this check is obsolete for C++23");
1781  diag::err_constexpr_non_literal_return,
1782  FD->isConsteval()))
1783  return false;
1784  return true;
1785 }
1786 
1787 /// Get diagnostic %select index for tag kind for
1788 /// record diagnostic message.
1789 /// WARNING: Indexes apply to particular diagnostics only!
1790 ///
1791 /// \returns diagnostic %select index.
1793  switch (Tag) {
1794  case TagTypeKind::Struct:
1795  return 0;
1797  return 1;
1798  case TagTypeKind::Class:
1799  return 2;
1800  default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1801  }
1802 }
1803 
1804 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1805  Stmt *Body,
1807 
1808 // Check whether a function declaration satisfies the requirements of a
1809 // constexpr function definition or a constexpr constructor definition. If so,
1810 // return true. If not, produce appropriate diagnostics (unless asked not to by
1811 // Kind) and return false.
1812 //
1813 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1816  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1817  if (MD && MD->isInstance()) {
1818  // C++11 [dcl.constexpr]p4:
1819  // The definition of a constexpr constructor shall satisfy the following
1820  // constraints:
1821  // - the class shall not have any virtual base classes;
1822  //
1823  // FIXME: This only applies to constructors and destructors, not arbitrary
1824  // member functions.
1825  const CXXRecordDecl *RD = MD->getParent();
1826  if (RD->getNumVBases()) {
1828  return false;
1829 
1830  Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1831  << isa<CXXConstructorDecl>(NewFD)
1833  for (const auto &I : RD->vbases())
1834  Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1835  << I.getSourceRange();
1836  return false;
1837  }
1838  }
1839 
1840  if (!isa<CXXConstructorDecl>(NewFD)) {
1841  // C++11 [dcl.constexpr]p3:
1842  // The definition of a constexpr function shall satisfy the following
1843  // constraints:
1844  // - it shall not be virtual; (removed in C++20)
1845  const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1846  if (Method && Method->isVirtual()) {
1847  if (getLangOpts().CPlusPlus20) {
1849  Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1850  } else {
1852  return false;
1853 
1854  Method = Method->getCanonicalDecl();
1855  Diag(Method->getLocation(), diag::err_constexpr_virtual);
1856 
1857  // If it's not obvious why this function is virtual, find an overridden
1858  // function which uses the 'virtual' keyword.
1859  const CXXMethodDecl *WrittenVirtual = Method;
1860  while (!WrittenVirtual->isVirtualAsWritten())
1861  WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1862  if (WrittenVirtual != Method)
1863  Diag(WrittenVirtual->getLocation(),
1864  diag::note_overridden_virtual_function);
1865  return false;
1866  }
1867  }
1868 
1869  // - its return type shall be a literal type; (removed in C++23)
1870  if (!getLangOpts().CPlusPlus23 &&
1871  !CheckConstexprReturnType(*this, NewFD, Kind))
1872  return false;
1873  }
1874 
1875  if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1876  // A destructor can be constexpr only if the defaulted destructor could be;
1877  // we don't need to check the members and bases if we already know they all
1878  // have constexpr destructors. (removed in C++23)
1879  if (!getLangOpts().CPlusPlus23 &&
1880  !Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1882  return false;
1883  if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1884  return false;
1885  }
1886  }
1887 
1888  // - each of its parameter types shall be a literal type; (removed in C++23)
1889  if (!getLangOpts().CPlusPlus23 &&
1890  !CheckConstexprParameterTypes(*this, NewFD, Kind))
1891  return false;
1892 
1893  Stmt *Body = NewFD->getBody();
1894  assert(Body &&
1895  "CheckConstexprFunctionDefinition called on function with no body");
1896  return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1897 }
1898 
1899 /// Check the given declaration statement is legal within a constexpr function
1900 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1901 ///
1902 /// \return true if the body is OK (maybe only as an extension), false if we
1903 /// have diagnosed a problem.
1905  DeclStmt *DS, SourceLocation &Cxx1yLoc,
1907  // C++11 [dcl.constexpr]p3 and p4:
1908  // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1909  // contain only
1910  for (const auto *DclIt : DS->decls()) {
1911  switch (DclIt->getKind()) {
1912  case Decl::StaticAssert:
1913  case Decl::Using:
1914  case Decl::UsingShadow:
1915  case Decl::UsingDirective:
1916  case Decl::UnresolvedUsingTypename:
1917  case Decl::UnresolvedUsingValue:
1918  case Decl::UsingEnum:
1919  // - static_assert-declarations
1920  // - using-declarations,
1921  // - using-directives,
1922  // - using-enum-declaration
1923  continue;
1924 
1925  case Decl::Typedef:
1926  case Decl::TypeAlias: {
1927  // - typedef declarations and alias-declarations that do not define
1928  // classes or enumerations,
1929  const auto *TN = cast<TypedefNameDecl>(DclIt);
1930  if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1931  // Don't allow variably-modified types in constexpr functions.
1933  TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1934  SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1935  << TL.getSourceRange() << TL.getType()
1936  << isa<CXXConstructorDecl>(Dcl);
1937  }
1938  return false;
1939  }
1940  continue;
1941  }
1942 
1943  case Decl::Enum:
1944  case Decl::CXXRecord:
1945  // C++1y allows types to be defined, not just declared.
1946  if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1948  SemaRef.Diag(DS->getBeginLoc(),
1949  SemaRef.getLangOpts().CPlusPlus14
1950  ? diag::warn_cxx11_compat_constexpr_type_definition
1951  : diag::ext_constexpr_type_definition)
1952  << isa<CXXConstructorDecl>(Dcl);
1953  } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1954  return false;
1955  }
1956  }
1957  continue;
1958 
1959  case Decl::EnumConstant:
1960  case Decl::IndirectField:
1961  case Decl::ParmVar:
1962  // These can only appear with other declarations which are banned in
1963  // C++11 and permitted in C++1y, so ignore them.
1964  continue;
1965 
1966  case Decl::Var:
1967  case Decl::Decomposition: {
1968  // C++1y [dcl.constexpr]p3 allows anything except:
1969  // a definition of a variable of non-literal type or of static or
1970  // thread storage duration or [before C++2a] for which no
1971  // initialization is performed.
1972  const auto *VD = cast<VarDecl>(DclIt);
1973  if (VD->isThisDeclarationADefinition()) {
1974  if (VD->isStaticLocal()) {
1976  SemaRef.Diag(VD->getLocation(),
1977  SemaRef.getLangOpts().CPlusPlus23
1978  ? diag::warn_cxx20_compat_constexpr_var
1979  : diag::ext_constexpr_static_var)
1980  << isa<CXXConstructorDecl>(Dcl)
1981  << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1982  } else if (!SemaRef.getLangOpts().CPlusPlus23) {
1983  return false;
1984  }
1985  }
1986  if (SemaRef.LangOpts.CPlusPlus23) {
1987  CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1988  diag::warn_cxx20_compat_constexpr_var,
1989  isa<CXXConstructorDecl>(Dcl),
1990  /*variable of non-literal type*/ 2);
1991  } else if (CheckLiteralType(
1992  SemaRef, Kind, VD->getLocation(), VD->getType(),
1993  diag::err_constexpr_local_var_non_literal_type,
1994  isa<CXXConstructorDecl>(Dcl))) {
1995  return false;
1996  }
1997  if (!VD->getType()->isDependentType() &&
1998  !VD->hasInit() && !VD->isCXXForRangeDecl()) {
2000  SemaRef.Diag(
2001  VD->getLocation(),
2002  SemaRef.getLangOpts().CPlusPlus20
2003  ? diag::warn_cxx17_compat_constexpr_local_var_no_init
2004  : diag::ext_constexpr_local_var_no_init)
2005  << isa<CXXConstructorDecl>(Dcl);
2006  } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2007  return false;
2008  }
2009  continue;
2010  }
2011  }
2013  SemaRef.Diag(VD->getLocation(),
2014  SemaRef.getLangOpts().CPlusPlus14
2015  ? diag::warn_cxx11_compat_constexpr_local_var
2016  : diag::ext_constexpr_local_var)
2017  << isa<CXXConstructorDecl>(Dcl);
2018  } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2019  return false;
2020  }
2021  continue;
2022  }
2023 
2024  case Decl::NamespaceAlias:
2025  case Decl::Function:
2026  // These are disallowed in C++11 and permitted in C++1y. Allow them
2027  // everywhere as an extension.
2028  if (!Cxx1yLoc.isValid())
2029  Cxx1yLoc = DS->getBeginLoc();
2030  continue;
2031 
2032  default:
2034  SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2035  << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2036  }
2037  return false;
2038  }
2039  }
2040 
2041  return true;
2042 }
2043 
2044 /// Check that the given field is initialized within a constexpr constructor.
2045 ///
2046 /// \param Dcl The constexpr constructor being checked.
2047 /// \param Field The field being checked. This may be a member of an anonymous
2048 /// struct or union nested within the class being checked.
2049 /// \param Inits All declarations, including anonymous struct/union members and
2050 /// indirect members, for which any initialization was provided.
2051 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2052 /// multiple notes for different members to the same error.
2053 /// \param Kind Whether we're diagnosing a constructor as written or determining
2054 /// whether the formal requirements are satisfied.
2055 /// \return \c false if we're checking for validity and the constructor does
2056 /// not satisfy the requirements on a constexpr constructor.
2058  const FunctionDecl *Dcl,
2059  FieldDecl *Field,
2060  llvm::SmallSet<Decl*, 16> &Inits,
2061  bool &Diagnosed,
2063  // In C++20 onwards, there's nothing to check for validity.
2065  SemaRef.getLangOpts().CPlusPlus20)
2066  return true;
2067 
2068  if (Field->isInvalidDecl())
2069  return true;
2070 
2071  if (Field->isUnnamedBitField())
2072  return true;
2073 
2074  // Anonymous unions with no variant members and empty anonymous structs do not
2075  // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2076  // indirect fields don't need initializing.
2077  if (Field->isAnonymousStructOrUnion() &&
2078  (Field->getType()->isUnionType()
2079  ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2080  : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2081  return true;
2082 
2083  if (!Inits.count(Field)) {
2085  if (!Diagnosed) {
2086  SemaRef.Diag(Dcl->getLocation(),
2087  SemaRef.getLangOpts().CPlusPlus20
2088  ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
2089  : diag::ext_constexpr_ctor_missing_init);
2090  Diagnosed = true;
2091  }
2092  SemaRef.Diag(Field->getLocation(),
2093  diag::note_constexpr_ctor_missing_init);
2094  } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2095  return false;
2096  }
2097  } else if (Field->isAnonymousStructOrUnion()) {
2098  const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2099  for (auto *I : RD->fields())
2100  // If an anonymous union contains an anonymous struct of which any member
2101  // is initialized, all members must be initialized.
2102  if (!RD->isUnion() || Inits.count(I))
2103  if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2104  Kind))
2105  return false;
2106  }
2107  return true;
2108 }
2109 
2110 /// Check the provided statement is allowed in a constexpr function
2111 /// definition.
2112 static bool
2114  SmallVectorImpl<SourceLocation> &ReturnStmts,
2115  SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2116  SourceLocation &Cxx2bLoc,
2118  // - its function-body shall be [...] a compound-statement that contains only
2119  switch (S->getStmtClass()) {
2120  case Stmt::NullStmtClass:
2121  // - null statements,
2122  return true;
2123 
2124  case Stmt::DeclStmtClass:
2125  // - static_assert-declarations
2126  // - using-declarations,
2127  // - using-directives,
2128  // - typedef declarations and alias-declarations that do not define
2129  // classes or enumerations,
2130  if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2131  return false;
2132  return true;
2133 
2134  case Stmt::ReturnStmtClass:
2135  // - and exactly one return statement;
2136  if (isa<CXXConstructorDecl>(Dcl)) {
2137  // C++1y allows return statements in constexpr constructors.
2138  if (!Cxx1yLoc.isValid())
2139  Cxx1yLoc = S->getBeginLoc();
2140  return true;
2141  }
2142 
2143  ReturnStmts.push_back(S->getBeginLoc());
2144  return true;
2145 
2146  case Stmt::AttributedStmtClass:
2147  // Attributes on a statement don't affect its formal kind and hence don't
2148  // affect its validity in a constexpr function.
2150  SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2151  Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2152 
2153  case Stmt::CompoundStmtClass: {
2154  // C++1y allows compound-statements.
2155  if (!Cxx1yLoc.isValid())
2156  Cxx1yLoc = S->getBeginLoc();
2157 
2158  CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2159  for (auto *BodyIt : CompStmt->body()) {
2160  if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2161  Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2162  return false;
2163  }
2164  return true;
2165  }
2166 
2167  case Stmt::IfStmtClass: {
2168  // C++1y allows if-statements.
2169  if (!Cxx1yLoc.isValid())
2170  Cxx1yLoc = S->getBeginLoc();
2171 
2172  IfStmt *If = cast<IfStmt>(S);
2173  if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2174  Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2175  return false;
2176  if (If->getElse() &&
2177  !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2178  Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2179  return false;
2180  return true;
2181  }
2182 
2183  case Stmt::WhileStmtClass:
2184  case Stmt::DoStmtClass:
2185  case Stmt::ForStmtClass:
2186  case Stmt::CXXForRangeStmtClass:
2187  case Stmt::ContinueStmtClass:
2188  // C++1y allows all of these. We don't allow them as extensions in C++11,
2189  // because they don't make sense without variable mutation.
2190  if (!SemaRef.getLangOpts().CPlusPlus14)
2191  break;
2192  if (!Cxx1yLoc.isValid())
2193  Cxx1yLoc = S->getBeginLoc();
2194  for (Stmt *SubStmt : S->children()) {
2195  if (SubStmt &&
2196  !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2197  Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2198  return false;
2199  }
2200  return true;
2201 
2202  case Stmt::SwitchStmtClass:
2203  case Stmt::CaseStmtClass:
2204  case Stmt::DefaultStmtClass:
2205  case Stmt::BreakStmtClass:
2206  // C++1y allows switch-statements, and since they don't need variable
2207  // mutation, we can reasonably allow them in C++11 as an extension.
2208  if (!Cxx1yLoc.isValid())
2209  Cxx1yLoc = S->getBeginLoc();
2210  for (Stmt *SubStmt : S->children()) {
2211  if (SubStmt &&
2212  !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2213  Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2214  return false;
2215  }
2216  return true;
2217 
2218  case Stmt::LabelStmtClass:
2219  case Stmt::GotoStmtClass:
2220  if (Cxx2bLoc.isInvalid())
2221  Cxx2bLoc = S->getBeginLoc();
2222  for (Stmt *SubStmt : S->children()) {
2223  if (SubStmt &&
2224  !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2225  Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2226  return false;
2227  }
2228  return true;
2229 
2230  case Stmt::GCCAsmStmtClass:
2231  case Stmt::MSAsmStmtClass:
2232  // C++2a allows inline assembly statements.
2233  case Stmt::CXXTryStmtClass:
2234  if (Cxx2aLoc.isInvalid())
2235  Cxx2aLoc = S->getBeginLoc();
2236  for (Stmt *SubStmt : S->children()) {
2237  if (SubStmt &&
2238  !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2239  Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2240  return false;
2241  }
2242  return true;
2243 
2244  case Stmt::CXXCatchStmtClass:
2245  // Do not bother checking the language mode (already covered by the
2246  // try block check).
2248  SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2249  Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2250  return false;
2251  return true;
2252 
2253  default:
2254  if (!isa<Expr>(S))
2255  break;
2256 
2257  // C++1y allows expression-statements.
2258  if (!Cxx1yLoc.isValid())
2259  Cxx1yLoc = S->getBeginLoc();
2260  return true;
2261  }
2262 
2264  SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2265  << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2266  }
2267  return false;
2268 }
2269 
2270 /// Check the body for the given constexpr function declaration only contains
2271 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2272 ///
2273 /// \return true if the body is OK, false if we have found or diagnosed a
2274 /// problem.
2276  Stmt *Body,
2278  SmallVector<SourceLocation, 4> ReturnStmts;
2279 
2280  if (isa<CXXTryStmt>(Body)) {
2281  // C++11 [dcl.constexpr]p3:
2282  // The definition of a constexpr function shall satisfy the following
2283  // constraints: [...]
2284  // - its function-body shall be = delete, = default, or a
2285  // compound-statement
2286  //
2287  // C++11 [dcl.constexpr]p4:
2288  // In the definition of a constexpr constructor, [...]
2289  // - its function-body shall not be a function-try-block;
2290  //
2291  // This restriction is lifted in C++2a, as long as inner statements also
2292  // apply the general constexpr rules.
2293  switch (Kind) {
2295  if (!SemaRef.getLangOpts().CPlusPlus20)
2296  return false;
2297  break;
2298 
2300  SemaRef.Diag(Body->getBeginLoc(),
2301  !SemaRef.getLangOpts().CPlusPlus20
2302  ? diag::ext_constexpr_function_try_block_cxx20
2303  : diag::warn_cxx17_compat_constexpr_function_try_block)
2304  << isa<CXXConstructorDecl>(Dcl);
2305  break;
2306  }
2307  }
2308 
2309  // - its function-body shall be [...] a compound-statement that contains only
2310  // [... list of cases ...]
2311  //
2312  // Note that walking the children here is enough to properly check for
2313  // CompoundStmt and CXXTryStmt body.
2314  SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2315  for (Stmt *SubStmt : Body->children()) {
2316  if (SubStmt &&
2317  !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2318  Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2319  return false;
2320  }
2321 
2323  // If this is only valid as an extension, report that we don't satisfy the
2324  // constraints of the current language.
2325  if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2326  (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2327  (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2328  return false;
2329  } else if (Cxx2bLoc.isValid()) {
2330  SemaRef.Diag(Cxx2bLoc,
2331  SemaRef.getLangOpts().CPlusPlus23
2332  ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
2333  : diag::ext_constexpr_body_invalid_stmt_cxx23)
2334  << isa<CXXConstructorDecl>(Dcl);
2335  } else if (Cxx2aLoc.isValid()) {
2336  SemaRef.Diag(Cxx2aLoc,
2337  SemaRef.getLangOpts().CPlusPlus20
2338  ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2339  : diag::ext_constexpr_body_invalid_stmt_cxx20)
2340  << isa<CXXConstructorDecl>(Dcl);
2341  } else if (Cxx1yLoc.isValid()) {
2342  SemaRef.Diag(Cxx1yLoc,
2343  SemaRef.getLangOpts().CPlusPlus14
2344  ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2345  : diag::ext_constexpr_body_invalid_stmt)
2346  << isa<CXXConstructorDecl>(Dcl);
2347  }
2348 
2349  if (const CXXConstructorDecl *Constructor
2350  = dyn_cast<CXXConstructorDecl>(Dcl)) {
2351  const CXXRecordDecl *RD = Constructor->getParent();
2352  // DR1359:
2353  // - every non-variant non-static data member and base class sub-object
2354  // shall be initialized;
2355  // DR1460:
2356  // - if the class is a union having variant members, exactly one of them
2357  // shall be initialized;
2358  if (RD->isUnion()) {
2359  if (Constructor->getNumCtorInitializers() == 0 &&
2360  RD->hasVariantMembers()) {
2362  SemaRef.Diag(
2363  Dcl->getLocation(),
2364  SemaRef.getLangOpts().CPlusPlus20
2365  ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2366  : diag::ext_constexpr_union_ctor_no_init);
2367  } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2368  return false;
2369  }
2370  }
2371  } else if (!Constructor->isDependentContext() &&
2372  !Constructor->isDelegatingConstructor()) {
2373  assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2374 
2375  // Skip detailed checking if we have enough initializers, and we would
2376  // allow at most one initializer per member.
2377  bool AnyAnonStructUnionMembers = false;
2378  unsigned Fields = 0;
2380  E = RD->field_end(); I != E; ++I, ++Fields) {
2381  if (I->isAnonymousStructOrUnion()) {
2382  AnyAnonStructUnionMembers = true;
2383  break;
2384  }
2385  }
2386  // DR1460:
2387  // - if the class is a union-like class, but is not a union, for each of
2388  // its anonymous union members having variant members, exactly one of
2389  // them shall be initialized;
2390  if (AnyAnonStructUnionMembers ||
2391  Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2392  // Check initialization of non-static data members. Base classes are
2393  // always initialized so do not need to be checked. Dependent bases
2394  // might not have initializers in the member initializer list.
2395  llvm::SmallSet<Decl*, 16> Inits;
2396  for (const auto *I: Constructor->inits()) {
2397  if (FieldDecl *FD = I->getMember())
2398  Inits.insert(FD);
2399  else if (IndirectFieldDecl *ID = I->getIndirectMember())
2400  Inits.insert(ID->chain_begin(), ID->chain_end());
2401  }
2402 
2403  bool Diagnosed = false;
2404  for (auto *I : RD->fields())
2405  if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2406  Kind))
2407  return false;
2408  }
2409  }
2410  } else {
2411  if (ReturnStmts.empty()) {
2412  // C++1y doesn't require constexpr functions to contain a 'return'
2413  // statement. We still do, unless the return type might be void, because
2414  // otherwise if there's no return statement, the function cannot
2415  // be used in a core constant expression.
2416  bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2417  (Dcl->getReturnType()->isVoidType() ||
2418  Dcl->getReturnType()->isDependentType());
2419  switch (Kind) {
2421  SemaRef.Diag(Dcl->getLocation(),
2422  OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2423  : diag::err_constexpr_body_no_return)
2424  << Dcl->isConsteval();
2425  if (!OK)
2426  return false;
2427  break;
2428 
2430  // The formal requirements don't include this rule in C++14, even
2431  // though the "must be able to produce a constant expression" rules
2432  // still imply it in some cases.
2433  if (!SemaRef.getLangOpts().CPlusPlus14)
2434  return false;
2435  break;
2436  }
2437  } else if (ReturnStmts.size() > 1) {
2438  switch (Kind) {
2440  SemaRef.Diag(
2441  ReturnStmts.back(),
2442  SemaRef.getLangOpts().CPlusPlus14
2443  ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2444  : diag::ext_constexpr_body_multiple_return);
2445  for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2446  SemaRef.Diag(ReturnStmts[I],
2447  diag::note_constexpr_body_previous_return);
2448  break;
2449 
2451  if (!SemaRef.getLangOpts().CPlusPlus14)
2452  return false;
2453  break;
2454  }
2455  }
2456  }
2457 
2458  // C++11 [dcl.constexpr]p5:
2459  // if no function argument values exist such that the function invocation
2460  // substitution would produce a constant expression, the program is
2461  // ill-formed; no diagnostic required.
2462  // C++11 [dcl.constexpr]p3:
2463  // - every constructor call and implicit conversion used in initializing the
2464  // return value shall be one of those allowed in a constant expression.
2465  // C++11 [dcl.constexpr]p4:
2466  // - every constructor involved in initializing non-static data members and
2467  // base class sub-objects shall be a constexpr constructor.
2468  //
2469  // Note that this rule is distinct from the "requirements for a constexpr
2470  // function", so is not checked in CheckValid mode.
2474  !SemaRef.getLangOpts().CPlusPlus23) {
2475  SemaRef.Diag(Dcl->getLocation(),
2476  diag::ext_constexpr_function_never_constant_expr)
2477  << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval()
2478  << Dcl->getNameInfo().getSourceRange();
2479  for (size_t I = 0, N = Diags.size(); I != N; ++I)
2480  SemaRef.Diag(Diags[I].first, Diags[I].second);
2481  // Don't return false here: we allow this for compatibility in
2482  // system headers.
2483  }
2484 
2485  return true;
2486 }
2487 
2489  FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2491  return true;
2495  auto it = UndefinedButUsed.find(FD->getCanonicalDecl());
2496  if (it != UndefinedButUsed.end()) {
2497  Diag(it->second, diag::err_immediate_function_used_before_definition)
2498  << it->first;
2499  Diag(FD->getLocation(), diag::note_defined_here) << FD;
2500  if (FD->isImmediateFunction() && !FD->isConsteval())
2502  return false;
2503  }
2504  }
2505  return true;
2506 }
2507 
2509  assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2510  "expected an immediate function");
2511  assert(FD->hasBody() && "expected the function to have a body");
2512  struct ImmediateEscalatingExpressionsVisitor
2513  : public RecursiveASTVisitor<ImmediateEscalatingExpressionsVisitor> {
2514 
2516  Sema &SemaRef;
2517 
2518  const FunctionDecl *ImmediateFn;
2519  bool ImmediateFnIsConstructor;
2520  CXXConstructorDecl *CurrentConstructor = nullptr;
2521  CXXCtorInitializer *CurrentInit = nullptr;
2522 
2523  ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2524  : SemaRef(SemaRef), ImmediateFn(FD),
2525  ImmediateFnIsConstructor(isa<CXXConstructorDecl>(FD)) {}
2526 
2527  bool shouldVisitImplicitCode() const { return true; }
2528  bool shouldVisitLambdaBody() const { return false; }
2529 
2530  void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2531  SourceLocation Loc = E->getBeginLoc();
2532  SourceRange Range = E->getSourceRange();
2533  if (CurrentConstructor && CurrentInit) {
2534  Loc = CurrentConstructor->getLocation();
2535  Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2536  : SourceRange();
2537  }
2538 
2539  FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2540 
2541  SemaRef.Diag(Loc, diag::note_immediate_function_reason)
2542  << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2543  << isa<CXXConstructorDecl>(Fn) << ImmediateFnIsConstructor
2544  << (InitializedField != nullptr)
2545  << (CurrentInit && !CurrentInit->isWritten())
2546  << InitializedField << Range;
2547  }
2548  bool TraverseCallExpr(CallExpr *E) {
2549  if (const auto *DR =
2550  dyn_cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit());
2551  DR && DR->isImmediateEscalating()) {
2552  Diag(E, E->getDirectCallee(), /*IsCall=*/true);
2553  return false;
2554  }
2555 
2556  for (Expr *A : E->arguments())
2557  if (!getDerived().TraverseStmt(A))
2558  return false;
2559 
2560  return true;
2561  }
2562 
2563  bool VisitDeclRefExpr(DeclRefExpr *E) {
2564  if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(E->getDecl());
2565  ReferencedFn && E->isImmediateEscalating()) {
2566  Diag(E, ReferencedFn, /*IsCall=*/false);
2567  return false;
2568  }
2569 
2570  return true;
2571  }
2572 
2573  bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2575  if (E->isImmediateEscalating()) {
2576  Diag(E, D, /*IsCall=*/true);
2577  return false;
2578  }
2579  return true;
2580  }
2581 
2582  bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
2583  llvm::SaveAndRestore RAII(CurrentInit, Init);
2584  return Base::TraverseConstructorInitializer(Init);
2585  }
2586 
2587  bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) {
2588  llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2589  return Base::TraverseCXXConstructorDecl(Ctr);
2590  }
2591 
2592  bool TraverseType(QualType T) { return true; }
2593  bool VisitBlockExpr(BlockExpr *T) { return true; }
2594 
2595  } Visitor(*this, FD);
2596  Visitor.TraverseDecl(FD);
2597 }
2598 
2599 /// Get the class that is directly named by the current context. This is the
2600 /// class for which an unqualified-id in this scope could name a constructor
2601 /// or destructor.
2602 ///
2603 /// If the scope specifier denotes a class, this will be that class.
2604 /// If the scope specifier is empty, this will be the class whose
2605 /// member-specification we are currently within. Otherwise, there
2606 /// is no such class.
2608  assert(getLangOpts().CPlusPlus && "No class names in C!");
2609 
2610  if (SS && SS->isInvalid())
2611  return nullptr;
2612 
2613  if (SS && SS->isNotEmpty()) {
2614  DeclContext *DC = computeDeclContext(*SS, true);
2615  return dyn_cast_or_null<CXXRecordDecl>(DC);
2616  }
2617 
2618  return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2619 }
2620 
2621 /// isCurrentClassName - Determine whether the identifier II is the
2622 /// name of the class type currently being defined. In the case of
2623 /// nested classes, this will only return true if II is the name of
2624 /// the innermost class.
2626  const CXXScopeSpec *SS) {
2627  CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2628  return CurDecl && &II == CurDecl->getIdentifier();
2629 }
2630 
2631 /// Determine whether the identifier II is a typo for the name of
2632 /// the class type currently being defined. If so, update it to the identifier
2633 /// that should have been used.
2635  assert(getLangOpts().CPlusPlus && "No class names in C!");
2636 
2637  if (!getLangOpts().SpellChecking)
2638  return false;
2639 
2640  CXXRecordDecl *CurDecl;
2641  if (SS && SS->isSet() && !SS->isInvalid()) {
2642  DeclContext *DC = computeDeclContext(*SS, true);
2643  CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2644  } else
2645  CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2646 
2647  if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2648  3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2649  < II->getLength()) {
2650  II = CurDecl->getIdentifier();
2651  return true;
2652  }
2653 
2654  return false;
2655 }
2656 
2657 /// Determine whether the given class is a base class of the given
2658 /// class, including looking at dependent bases.
2659 static bool findCircularInheritance(const CXXRecordDecl *Class,
2660  const CXXRecordDecl *Current) {
2662 
2663  Class = Class->getCanonicalDecl();
2664  while (true) {
2665  for (const auto &I : Current->bases()) {
2666  CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2667  if (!Base)
2668  continue;
2669 
2670  Base = Base->getDefinition();
2671  if (!Base)
2672  continue;
2673 
2674  if (Base->getCanonicalDecl() == Class)
2675  return true;
2676 
2677  Queue.push_back(Base);
2678  }
2679 
2680  if (Queue.empty())
2681  return false;
2682 
2683  Current = Queue.pop_back_val();
2684  }
2685 
2686  return false;
2687 }
2688 
2689 /// Check the validity of a C++ base class specifier.
2690 ///
2691 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2692 /// and returns NULL otherwise.
2695  SourceRange SpecifierRange,
2696  bool Virtual, AccessSpecifier Access,
2697  TypeSourceInfo *TInfo,
2698  SourceLocation EllipsisLoc) {
2699  // In HLSL, unspecified class access is public rather than private.
2700  if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2701  Access == AS_none)
2702  Access = AS_public;
2703 
2704  QualType BaseType = TInfo->getType();
2705  if (BaseType->containsErrors()) {
2706  // Already emitted a diagnostic when parsing the error type.
2707  return nullptr;
2708  }
2709  // C++ [class.union]p1:
2710  // A union shall not have base classes.
2711  if (Class->isUnion()) {
2712  Diag(Class->getLocation(), diag::err_base_clause_on_union)
2713  << SpecifierRange;
2714  return nullptr;
2715  }
2716 
2717  if (EllipsisLoc.isValid() &&
2719  Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2720  << TInfo->getTypeLoc().getSourceRange();
2721  EllipsisLoc = SourceLocation();
2722  }
2723 
2724  SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2725 
2726  if (BaseType->isDependentType()) {
2727  // Make sure that we don't have circular inheritance among our dependent
2728  // bases. For non-dependent bases, the check for completeness below handles
2729  // this.
2730  if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2731  if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2732  ((BaseDecl = BaseDecl->getDefinition()) &&
2733  findCircularInheritance(Class, BaseDecl))) {
2734  Diag(BaseLoc, diag::err_circular_inheritance)
2735  << BaseType << Context.getTypeDeclType(Class);
2736 
2737  if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2738  Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2739  << BaseType;
2740 
2741  return nullptr;
2742  }
2743  }
2744 
2745  // Make sure that we don't make an ill-formed AST where the type of the
2746  // Class is non-dependent and its attached base class specifier is an
2747  // dependent type, which violates invariants in many clang code paths (e.g.
2748  // constexpr evaluator). If this case happens (in errory-recovery mode), we
2749  // explicitly mark the Class decl invalid. The diagnostic was already
2750  // emitted.
2751  if (!Class->getTypeForDecl()->isDependentType())
2752  Class->setInvalidDecl();
2753  return new (Context) CXXBaseSpecifier(
2754  SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2755  Access, TInfo, EllipsisLoc);
2756  }
2757 
2758  // Base specifiers must be record types.
2759  if (!BaseType->isRecordType()) {
2760  Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2761  return nullptr;
2762  }
2763 
2764  // C++ [class.union]p1:
2765  // A union shall not be used as a base class.
2766  if (BaseType->isUnionType()) {
2767  Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2768  return nullptr;
2769  }
2770 
2771  // For the MS ABI, propagate DLL attributes to base class templates.
2773  Context.getTargetInfo().getTriple().isPS()) {
2774  if (Attr *ClassAttr = getDLLAttr(Class)) {
2775  if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2776  BaseType->getAsCXXRecordDecl())) {
2777  propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2778  BaseLoc);
2779  }
2780  }
2781  }
2782 
2783  // C++ [class.derived]p2:
2784  // The class-name in a base-specifier shall not be an incompletely
2785  // defined class.
2786  if (RequireCompleteType(BaseLoc, BaseType,
2787  diag::err_incomplete_base_class, SpecifierRange)) {
2788  Class->setInvalidDecl();
2789  return nullptr;
2790  }
2791 
2792  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2793  RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2794  assert(BaseDecl && "Record type has no declaration");
2795  BaseDecl = BaseDecl->getDefinition();
2796  assert(BaseDecl && "Base type is not incomplete, but has no definition");
2797  CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2798  assert(CXXBaseDecl && "Base type is not a C++ type");
2799 
2800  // Microsoft docs say:
2801  // "If a base-class has a code_seg attribute, derived classes must have the
2802  // same attribute."
2803  const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2804  const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2805  if ((DerivedCSA || BaseCSA) &&
2806  (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2807  Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2808  Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2809  << CXXBaseDecl;
2810  return nullptr;
2811  }
2812 
2813  // A class which contains a flexible array member is not suitable for use as a
2814  // base class:
2815  // - If the layout determines that a base comes before another base,
2816  // the flexible array member would index into the subsequent base.
2817  // - If the layout determines that base comes before the derived class,
2818  // the flexible array member would index into the derived class.
2819  if (CXXBaseDecl->hasFlexibleArrayMember()) {
2820  Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2821  << CXXBaseDecl->getDeclName();
2822  return nullptr;
2823  }
2824 
2825  // C++ [class]p3:
2826  // If a class is marked final and it appears as a base-type-specifier in
2827  // base-clause, the program is ill-formed.
2828  if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2829  Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2830  << CXXBaseDecl->getDeclName()
2831  << FA->isSpelledAsSealed();
2832  Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2833  << CXXBaseDecl->getDeclName() << FA->getRange();
2834  return nullptr;
2835  }
2836 
2837  if (BaseDecl->isInvalidDecl())
2838  Class->setInvalidDecl();
2839 
2840  // Create the base specifier.
2841  return new (Context) CXXBaseSpecifier(
2842  SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2843  Access, TInfo, EllipsisLoc);
2844 }
2845 
2846 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2847 /// one entry in the base class list of a class specifier, for
2848 /// example:
2849 /// class foo : public bar, virtual private baz {
2850 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2852  const ParsedAttributesView &Attributes,
2853  bool Virtual, AccessSpecifier Access,
2854  ParsedType basetype, SourceLocation BaseLoc,
2855  SourceLocation EllipsisLoc) {
2856  if (!classdecl)
2857  return true;
2858 
2859  AdjustDeclIfTemplate(classdecl);
2860  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2861  if (!Class)
2862  return true;
2863 
2864  // We haven't yet attached the base specifiers.
2865  Class->setIsParsingBaseSpecifiers();
2866 
2867  // We do not support any C++11 attributes on base-specifiers yet.
2868  // Diagnose any attributes we see.
2869  for (const ParsedAttr &AL : Attributes) {
2870  if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2871  continue;
2872  if (AL.getKind() == ParsedAttr::UnknownAttribute)
2873  Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
2874  << AL << AL.getRange();
2875  else
2876  Diag(AL.getLoc(), diag::err_base_specifier_attribute)
2877  << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2878  }
2879 
2880  TypeSourceInfo *TInfo = nullptr;
2881  GetTypeFromParser(basetype, &TInfo);
2882 
2883  if (EllipsisLoc.isInvalid() &&
2884  DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2885  UPPC_BaseType))
2886  return true;
2887 
2888  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2889  Virtual, Access, TInfo,
2890  EllipsisLoc))
2891  return BaseSpec;
2892  else
2893  Class->setInvalidDecl();
2894 
2895  return true;
2896 }
2897 
2898 /// Use small set to collect indirect bases. As this is only used
2899 /// locally, there's no need to abstract the small size parameter.
2901 
2902 /// Recursively add the bases of Type. Don't add Type itself.
2903 static void
2905  const QualType &Type)
2906 {
2907  // Even though the incoming type is a base, it might not be
2908  // a class -- it could be a template parm, for instance.
2909  if (auto Rec = Type->getAs<RecordType>()) {
2910  auto Decl = Rec->getAsCXXRecordDecl();
2911 
2912  // Iterate over its bases.
2913  for (const auto &BaseSpec : Decl->bases()) {
2914  QualType Base = Context.getCanonicalType(BaseSpec.getType())
2915  .getUnqualifiedType();
2916  if (Set.insert(Base).second)
2917  // If we've not already seen it, recurse.
2919  }
2920  }
2921 }
2922 
2923 /// Performs the actual work of attaching the given base class
2924 /// specifiers to a C++ class.
2927  if (Bases.empty())
2928  return false;
2929 
2930  // Used to keep track of which base types we have already seen, so
2931  // that we can properly diagnose redundant direct base types. Note
2932  // that the key is always the unqualified canonical type of the base
2933  // class.
2934  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2935 
2936  // Used to track indirect bases so we can see if a direct base is
2937  // ambiguous.
2938  IndirectBaseSet IndirectBaseTypes;
2939 
2940  // Copy non-redundant base specifiers into permanent storage.
2941  unsigned NumGoodBases = 0;
2942  bool Invalid = false;
2943  for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2944  QualType NewBaseType
2945  = Context.getCanonicalType(Bases[idx]->getType());
2946  NewBaseType = NewBaseType.getLocalUnqualifiedType();
2947 
2948  CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2949  if (KnownBase) {
2950  // C++ [class.mi]p3:
2951  // A class shall not be specified as a direct base class of a
2952  // derived class more than once.
2953  Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2954  << KnownBase->getType() << Bases[idx]->getSourceRange();
2955 
2956  // Delete the duplicate base class specifier; we're going to
2957  // overwrite its pointer later.
2958  Context.Deallocate(Bases[idx]);
2959 
2960  Invalid = true;
2961  } else {
2962  // Okay, add this new base class.
2963  KnownBase = Bases[idx];
2964  Bases[NumGoodBases++] = Bases[idx];
2965 
2966  if (NewBaseType->isDependentType())
2967  continue;
2968  // Note this base's direct & indirect bases, if there could be ambiguity.
2969  if (Bases.size() > 1)
2970  NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2971 
2972  if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2973  const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2974  if (Class->isInterface() &&
2975  (!RD->isInterfaceLike() ||
2976  KnownBase->getAccessSpecifier() != AS_public)) {
2977  // The Microsoft extension __interface does not permit bases that
2978  // are not themselves public interfaces.
2979  Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2980  << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2981  << RD->getSourceRange();
2982  Invalid = true;
2983  }
2984  if (RD->hasAttr<WeakAttr>())
2985  Class->addAttr(WeakAttr::CreateImplicit(Context));
2986  }
2987  }
2988  }
2989 
2990  // Attach the remaining base class specifiers to the derived class.
2991  Class->setBases(Bases.data(), NumGoodBases);
2992 
2993  // Check that the only base classes that are duplicate are virtual.
2994  for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2995  // Check whether this direct base is inaccessible due to ambiguity.
2996  QualType BaseType = Bases[idx]->getType();
2997 
2998  // Skip all dependent types in templates being used as base specifiers.
2999  // Checks below assume that the base specifier is a CXXRecord.
3000  if (BaseType->isDependentType())
3001  continue;
3002 
3003  CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
3004  .getUnqualifiedType();
3005 
3006  if (IndirectBaseTypes.count(CanonicalBase)) {
3007  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3008  /*DetectVirtual=*/true);
3009  bool found
3010  = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
3011  assert(found);
3012  (void)found;
3013 
3014  if (Paths.isAmbiguous(CanonicalBase))
3015  Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
3016  << BaseType << getAmbiguousPathsDisplayString(Paths)
3017  << Bases[idx]->getSourceRange();
3018  else
3019  assert(Bases[idx]->isVirtual());
3020  }
3021 
3022  // Delete the base class specifier, since its data has been copied
3023  // into the CXXRecordDecl.
3024  Context.Deallocate(Bases[idx]);
3025  }
3026 
3027  return Invalid;
3028 }
3029 
3030 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
3031 /// class, after checking whether there are any duplicate base
3032 /// classes.
3035  if (!ClassDecl || Bases.empty())
3036  return;
3037 
3038  AdjustDeclIfTemplate(ClassDecl);
3039  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
3040 }
3041 
3042 /// Determine whether the type \p Derived is a C++ class that is
3043 /// derived from the type \p Base.
3045  if (!getLangOpts().CPlusPlus)
3046  return false;
3047 
3048  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
3049  if (!DerivedRD)
3050  return false;
3051 
3052  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
3053  if (!BaseRD)
3054  return false;
3055 
3056  // If either the base or the derived type is invalid, don't try to
3057  // check whether one is derived from the other.
3058  if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
3059  return false;
3060 
3061  // FIXME: In a modules build, do we need the entire path to be visible for us
3062  // to be able to use the inheritance relationship?
3063  if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
3064  return false;
3065 
3066  return DerivedRD->isDerivedFrom(BaseRD);
3067 }
3068 
3069 /// Determine whether the type \p Derived is a C++ class that is
3070 /// derived from the type \p Base.
3072  CXXBasePaths &Paths) {
3073  if (!getLangOpts().CPlusPlus)
3074  return false;
3075 
3076  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
3077  if (!DerivedRD)
3078  return false;
3079 
3080  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
3081  if (!BaseRD)
3082  return false;
3083 
3084  if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
3085  return false;
3086 
3087  return DerivedRD->isDerivedFrom(BaseRD, Paths);
3088 }
3089 
3090 static void BuildBasePathArray(const CXXBasePath &Path,
3091  CXXCastPath &BasePathArray) {
3092  // We first go backward and check if we have a virtual base.
3093  // FIXME: It would be better if CXXBasePath had the base specifier for
3094  // the nearest virtual base.
3095  unsigned Start = 0;
3096  for (unsigned I = Path.size(); I != 0; --I) {
3097  if (Path[I - 1].Base->isVirtual()) {
3098  Start = I - 1;
3099  break;
3100  }
3101  }
3102 
3103  // Now add all bases.
3104  for (unsigned I = Start, E = Path.size(); I != E; ++I)
3105  BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
3106 }
3107 
3108 
3110  CXXCastPath &BasePathArray) {
3111  assert(BasePathArray.empty() && "Base path array must be empty!");
3112  assert(Paths.isRecordingPaths() && "Must record paths!");
3113  return ::BuildBasePathArray(Paths.front(), BasePathArray);
3114 }
3115 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
3116 /// conversion (where Derived and Base are class types) is
3117 /// well-formed, meaning that the conversion is unambiguous (and
3118 /// that all of the base classes are accessible). Returns true
3119 /// and emits a diagnostic if the code is ill-formed, returns false
3120 /// otherwise. Loc is the location where this routine should point to
3121 /// if there is an error, and Range is the source range to highlight
3122 /// if there is an error.
3123 ///
3124 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
3125 /// diagnostic for the respective type of error will be suppressed, but the
3126 /// check for ill-formed code will still be performed.
3127 bool
3129  unsigned InaccessibleBaseID,
3130  unsigned AmbiguousBaseConvID,
3131  SourceLocation Loc, SourceRange Range,
3132  DeclarationName Name,
3133  CXXCastPath *BasePath,
3134  bool IgnoreAccess) {
3135  // First, determine whether the path from Derived to Base is
3136  // ambiguous. This is slightly more expensive than checking whether
3137  // the Derived to Base conversion exists, because here we need to
3138  // explore multiple paths to determine if there is an ambiguity.
3139  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3140  /*DetectVirtual=*/false);
3141  bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3142  if (!DerivationOkay)
3143  return true;
3144 
3145  const CXXBasePath *Path = nullptr;
3146  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
3147  Path = &Paths.front();
3148 
3149  // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3150  // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3151  // user to access such bases.
3152  if (!Path && getLangOpts().MSVCCompat) {
3153  for (const CXXBasePath &PossiblePath : Paths) {
3154  if (PossiblePath.size() == 1) {
3155  Path = &PossiblePath;
3156  if (AmbiguousBaseConvID)
3157  Diag(Loc, diag::ext_ms_ambiguous_direct_base)
3158  << Base << Derived << Range;
3159  break;
3160  }
3161  }
3162  }
3163 
3164  if (Path) {
3165  if (!IgnoreAccess) {
3166  // Check that the base class can be accessed.
3167  switch (
3168  CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
3169  case AR_inaccessible:
3170  return true;
3171  case AR_accessible:
3172  case AR_dependent:
3173  case AR_delayed:
3174  break;
3175  }
3176  }
3177 
3178  // Build a base path if necessary.
3179  if (BasePath)
3180  ::BuildBasePathArray(*Path, *BasePath);
3181  return false;
3182  }
3183 
3184  if (AmbiguousBaseConvID) {
3185  // We know that the derived-to-base conversion is ambiguous, and
3186  // we're going to produce a diagnostic. Perform the derived-to-base
3187  // search just one more time to compute all of the possible paths so
3188  // that we can print them out. This is more expensive than any of
3189  // the previous derived-to-base checks we've done, but at this point
3190  // performance isn't as much of an issue.
3191  Paths.clear();
3192  Paths.setRecordingPaths(true);
3193  bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3194  assert(StillOkay && "Can only be used with a derived-to-base conversion");
3195  (void)StillOkay;
3196 
3197  // Build up a textual representation of the ambiguous paths, e.g.,
3198  // D -> B -> A, that will be used to illustrate the ambiguous
3199  // conversions in the diagnostic. We only print one of the paths
3200  // to each base class subobject.
3201  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3202 
3203  Diag(Loc, AmbiguousBaseConvID)
3204  << Derived << Base << PathDisplayStr << Range << Name;
3205  }
3206  return true;
3207 }
3208 
3209 bool
3211  SourceLocation Loc, SourceRange Range,
3212  CXXCastPath *BasePath,
3213  bool IgnoreAccess) {
3215  Derived, Base, diag::err_upcast_to_inaccessible_base,
3216  diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3217  BasePath, IgnoreAccess);
3218 }
3219 
3220 
3221 /// Builds a string representing ambiguous paths from a
3222 /// specific derived class to different subobjects of the same base
3223 /// class.
3224 ///
3225 /// This function builds a string that can be used in error messages
3226 /// to show the different paths that one can take through the
3227 /// inheritance hierarchy to go from the derived class to different
3228 /// subobjects of a base class. The result looks something like this:
3229 /// @code
3230 /// struct D -> struct B -> struct A
3231 /// struct D -> struct C -> struct A
3232 /// @endcode
3234  std::string PathDisplayStr;
3235  std::set<unsigned> DisplayedPaths;
3236  for (CXXBasePaths::paths_iterator Path = Paths.begin();
3237  Path != Paths.end(); ++Path) {
3238  if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3239  // We haven't displayed a path to this particular base
3240  // class subobject yet.
3241  PathDisplayStr += "\n ";
3242  PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3243  for (CXXBasePath::const_iterator Element = Path->begin();
3244  Element != Path->end(); ++Element)
3245  PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3246  }
3247  }
3248 
3249  return PathDisplayStr;
3250 }
3251 
3252 //===----------------------------------------------------------------------===//
3253 // C++ class member Handling
3254 //===----------------------------------------------------------------------===//
3255 
3256 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3258  SourceLocation ColonLoc,
3259  const ParsedAttributesView &Attrs) {
3260  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3262  ASLoc, ColonLoc);
3263  CurContext->addHiddenDecl(ASDecl);
3264  return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3265 }
3266 
3267 /// CheckOverrideControl - Check C++11 override control semantics.
3269  if (D->isInvalidDecl())
3270  return;
3271 
3272  // We only care about "override" and "final" declarations.
3273  if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3274  return;
3275 
3276  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3277 
3278  // We can't check dependent instance methods.
3279  if (MD && MD->isInstance() &&
3280  (MD->getParent()->hasAnyDependentBases() ||
3281  MD->getType()->isDependentType()))
3282  return;
3283 
3284  if (MD && !MD->isVirtual()) {
3285  // If we have a non-virtual method, check if it hides a virtual method.
3286  // (In that case, it's most likely the method has the wrong type.)
3287  SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3288  FindHiddenVirtualMethods(MD, OverloadedMethods);
3289 
3290  if (!OverloadedMethods.empty()) {
3291  if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3292  Diag(OA->getLocation(),
3293  diag::override_keyword_hides_virtual_member_function)
3294  << "override" << (OverloadedMethods.size() > 1);
3295  } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3296  Diag(FA->getLocation(),
3297  diag::override_keyword_hides_virtual_member_function)
3298  << (FA->isSpelledAsSealed() ? "sealed" : "final")
3299  << (OverloadedMethods.size() > 1);
3300  }
3301  NoteHiddenVirtualMethods(MD, OverloadedMethods);
3302  MD->setInvalidDecl();
3303  return;
3304  }
3305  // Fall through into the general case diagnostic.
3306  // FIXME: We might want to attempt typo correction here.
3307  }
3308 
3309  if (!MD || !MD->isVirtual()) {
3310  if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3311  Diag(OA->getLocation(),
3312  diag::override_keyword_only_allowed_on_virtual_member_functions)
3313  << "override" << FixItHint::CreateRemoval(OA->getLocation());
3314  D->dropAttr<OverrideAttr>();
3315  }
3316  if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3317  Diag(FA->getLocation(),
3318  diag::override_keyword_only_allowed_on_virtual_member_functions)
3319  << (FA->isSpelledAsSealed() ? "sealed" : "final")
3320  << FixItHint::CreateRemoval(FA->getLocation());
3321  D->dropAttr<FinalAttr>();
3322  }
3323  return;
3324  }
3325 
3326  // C++11 [class.virtual]p5:
3327  // If a function is marked with the virt-specifier override and
3328  // does not override a member function of a base class, the program is
3329  // ill-formed.
3330  bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3331  if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3332  Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3333  << MD->getDeclName();
3334 }
3335 
3337  if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3338  return;
3339  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3340  if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3341  return;
3342 
3343  SourceLocation Loc = MD->getLocation();
3344  SourceLocation SpellingLoc = Loc;
3345  if (getSourceManager().isMacroArgExpansion(Loc))
3346  SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3347  SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3348  if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3349  return;
3350 
3351  if (MD->size_overridden_methods() > 0) {
3352  auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3353  unsigned DiagID =
3354  Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3355  ? DiagInconsistent
3356  : DiagSuggest;
3357  Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3358  const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3359  Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3360  };
3361  if (isa<CXXDestructorDecl>(MD))
3362  EmitDiag(
3363  diag::warn_inconsistent_destructor_marked_not_override_overriding,
3364  diag::warn_suggest_destructor_marked_not_override_overriding);
3365  else
3366  EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3367  diag::warn_suggest_function_marked_not_override_overriding);
3368  }
3369 }
3370 
3371 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3372 /// function overrides a virtual member function marked 'final', according to
3373 /// C++11 [class.virtual]p4.
3375  const CXXMethodDecl *Old) {
3376  FinalAttr *FA = Old->getAttr<FinalAttr>();
3377  if (!FA)
3378  return false;
3379 
3380  Diag(New->getLocation(), diag::err_final_function_overridden)
3381  << New->getDeclName()
3382  << FA->isSpelledAsSealed();
3383  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3384  return true;
3385 }
3386 
3387 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3388  const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3389  // FIXME: Destruction of ObjC lifetime types has side-effects.
3390  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3391  return !RD->isCompleteDefinition() ||
3392  !RD->hasTrivialDefaultConstructor() ||
3393  !RD->hasTrivialDestructor();
3394  return false;
3395 }
3396 
3397 // Check if there is a field shadowing.
3398 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3399  DeclarationName FieldName,
3400  const CXXRecordDecl *RD,
3401  bool DeclIsField) {
3402  if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3403  return;
3404 
3405  // To record a shadowed field in a base
3406  std::map<CXXRecordDecl*, NamedDecl*> Bases;
3407  auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3408  CXXBasePath &Path) {
3409  const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3410  // Record an ambiguous path directly
3411  if (Bases.find(Base) != Bases.end())
3412  return true;
3413  for (const auto Field : Base->lookup(FieldName)) {
3414  if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3415  Field->getAccess() != AS_private) {
3416  assert(Field->getAccess() != AS_none);
3417  assert(Bases.find(Base) == Bases.end());
3418  Bases[Base] = Field;
3419  return true;
3420  }
3421  }
3422  return false;
3423  };
3424 
3425  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3426  /*DetectVirtual=*/true);
3427  if (!RD->lookupInBases(FieldShadowed, Paths))
3428  return;
3429 
3430  for (const auto &P : Paths) {
3431  auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3432  auto It = Bases.find(Base);
3433  // Skip duplicated bases
3434  if (It == Bases.end())
3435  continue;
3436  auto BaseField = It->second;
3437  assert(BaseField->getAccess() != AS_private);
3438  if (AS_none !=
3439  CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3440  Diag(Loc, diag::warn_shadow_field)
3441  << FieldName << RD << Base << DeclIsField;
3442  Diag(BaseField->getLocation(), diag::note_shadow_field);
3443  Bases.erase(It);
3444  }
3445  }
3446 }
3447 
3448 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3449 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3450 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3451 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3452 /// present (but parsing it has been deferred).
3453 NamedDecl *
3455  MultiTemplateParamsArg TemplateParameterLists,
3456  Expr *BW, const VirtSpecifiers &VS,
3457  InClassInitStyle InitStyle) {
3458  const DeclSpec &DS = D.getDeclSpec();
3460  DeclarationName Name = NameInfo.getName();
3461  SourceLocation Loc = NameInfo.getLoc();
3462 
3463  // For anonymous bitfields, the location should point to the type.
3464  if (Loc.isInvalid())
3465  Loc = D.getBeginLoc();
3466 
3467  Expr *BitWidth = static_cast<Expr*>(BW);
3468 
3469  assert(isa<CXXRecordDecl>(CurContext));
3470  assert(!DS.isFriendSpecified());
3471 
3472  bool isFunc = D.isDeclarationOfFunction();
3473  const ParsedAttr *MSPropertyAttr =
3475 
3476  if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3477  // The Microsoft extension __interface only permits public member functions
3478  // and prohibits constructors, destructors, operators, non-public member
3479  // functions, static methods and data members.
3480  unsigned InvalidDecl;
3481  bool ShowDeclName = true;
3482  if (!isFunc &&
3483  (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3484  InvalidDecl = 0;
3485  else if (!isFunc)
3486  InvalidDecl = 1;
3487  else if (AS != AS_public)
3488  InvalidDecl = 2;
3489  else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3490  InvalidDecl = 3;
3491  else switch (Name.getNameKind()) {
3493  InvalidDecl = 4;
3494  ShowDeclName = false;
3495  break;
3496 
3498  InvalidDecl = 5;
3499  ShowDeclName = false;
3500  break;
3501 
3504  InvalidDecl = 6;
3505  break;
3506 
3507  default:
3508  InvalidDecl = 0;
3509  break;
3510  }
3511 
3512  if (InvalidDecl) {
3513  if (ShowDeclName)
3514  Diag(Loc, diag::err_invalid_member_in_interface)
3515  << (InvalidDecl-1) << Name;
3516  else
3517  Diag(Loc, diag::err_invalid_member_in_interface)
3518  << (InvalidDecl-1) << "";
3519  return nullptr;
3520  }
3521  }
3522 
3523  // C++ 9.2p6: A member shall not be declared to have automatic storage
3524  // duration (auto, register) or with the extern storage-class-specifier.
3525  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3526  // data members and cannot be applied to names declared const or static,
3527  // and cannot be applied to reference members.
3528  switch (DS.getStorageClassSpec()) {
3530  case DeclSpec::SCS_typedef:
3531  case DeclSpec::SCS_static:
3532  break;
3533  case DeclSpec::SCS_mutable:
3534  if (isFunc) {
3535  Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3536 
3537  // FIXME: It would be nicer if the keyword was ignored only for this
3538  // declarator. Otherwise we could get follow-up errors.
3540  }
3541  break;
3542  default:
3544  diag::err_storageclass_invalid_for_member);
3546  break;
3547  }
3548 
3549  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3551  !isFunc);
3552 
3553  if (DS.hasConstexprSpecifier() && isInstField) {
3555  Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3556  SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3557  if (InitStyle == ICIS_NoInit) {
3558  B << 0 << 0;
3560  B << FixItHint::CreateRemoval(ConstexprLoc);
3561  else {
3562  B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3564  const char *PrevSpec;
3565  unsigned DiagID;
3566  bool Failed = D.getMutableDeclSpec().SetTypeQual(
3567  DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3568  (void)Failed;
3569  assert(!Failed && "Making a constexpr member const shouldn't fail");
3570  }
3571  } else {
3572  B << 1;
3573  const char *PrevSpec;
3574  unsigned DiagID;
3576  *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3578  assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3579  "This is the only DeclSpec that should fail to be applied");
3580  B << 1;
3581  } else {
3582  B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3583  isInstField = false;
3584  }
3585  }
3586  }
3587 
3588  NamedDecl *Member;
3589  if (isInstField) {
3590  CXXScopeSpec &SS = D.getCXXScopeSpec();
3591 
3592  // Data members must have identifiers for names.
3593  if (!Name.isIdentifier()) {
3594  Diag(Loc, diag::err_bad_variable_name)
3595  << Name;
3596  return nullptr;
3597  }
3598 
3599  IdentifierInfo *II = Name.getAsIdentifierInfo();
3600 
3601  // Member field could not be with "template" keyword.
3602  // So TemplateParameterLists should be empty in this case.
3603  if (TemplateParameterLists.size()) {
3604  TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3605  if (TemplateParams->size()) {
3606  // There is no such thing as a member field template.
3607  Diag(D.getIdentifierLoc(), diag::err_template_member)
3608  << II
3609  << SourceRange(TemplateParams->getTemplateLoc(),
3610  TemplateParams->getRAngleLoc());
3611  } else {
3612  // There is an extraneous 'template<>' for this member.
3613  Diag(TemplateParams->getTemplateLoc(),
3614  diag::err_template_member_noparams)
3615  << II
3616  << SourceRange(TemplateParams->getTemplateLoc(),
3617  TemplateParams->getRAngleLoc());
3618  }
3619  return nullptr;
3620  }
3621 
3623  Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3624  << II
3627  << D.getName().TemplateId->LAngleLoc;
3628  D.SetIdentifier(II, Loc);
3629  }
3630 
3631  if (SS.isSet() && !SS.isInvalid()) {
3632  // The user provided a superfluous scope specifier inside a class
3633  // definition:
3634  //
3635  // class X {
3636  // int X::member;
3637  // };
3638  if (DeclContext *DC = computeDeclContext(SS, false)) {
3639  TemplateIdAnnotation *TemplateId =
3641  ? D.getName().TemplateId
3642  : nullptr;
3644  TemplateId,
3645  /*IsMemberSpecialization=*/false);
3646  } else {
3647  Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3648  << Name << SS.getRange();
3649  }
3650  SS.clear();
3651  }
3652 
3653  if (MSPropertyAttr) {
3654  Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3655  BitWidth, InitStyle, AS, *MSPropertyAttr);
3656  if (!Member)
3657  return nullptr;
3658  isInstField = false;
3659  } else {
3660  Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3661  BitWidth, InitStyle, AS);
3662  if (!Member)
3663  return nullptr;
3664  }
3665 
3666  CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3667  } else {
3668  Member = HandleDeclarator(S, D, TemplateParameterLists);
3669  if (!Member)
3670  return nullptr;
3671 
3672  // Non-instance-fields can't have a bitfield.
3673  if (BitWidth) {
3674  if (Member->isInvalidDecl()) {
3675  // don't emit another diagnostic.
3676  } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3677  // C++ 9.6p3: A bit-field shall not be a static member.
3678  // "static member 'A' cannot be a bit-field"
3679  Diag(Loc, diag::err_static_not_bitfield)
3680  << Name << BitWidth->getSourceRange();
3681  } else if (isa<TypedefDecl>(Member)) {
3682  // "typedef member 'x' cannot be a bit-field"
3683  Diag(Loc, diag::err_typedef_not_bitfield)
3684  << Name << BitWidth->getSourceRange();
3685  } else {
3686  // A function typedef ("typedef int f(); f a;").
3687  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3688  Diag(Loc, diag::err_not_integral_type_bitfield)
3689  << Name << cast<ValueDecl>(Member)->getType()
3690  << BitWidth->getSourceRange();
3691  }
3692 
3693  BitWidth = nullptr;
3694  Member->setInvalidDecl();
3695  }
3696 
3697  NamedDecl *NonTemplateMember = Member;
3698  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3699  NonTemplateMember = FunTmpl->getTemplatedDecl();
3700  else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3701  NonTemplateMember = VarTmpl->getTemplatedDecl();
3702 
3703  Member->setAccess(AS);
3704 
3705  // If we have declared a member function template or static data member
3706  // template, set the access of the templated declaration as well.
3707  if (NonTemplateMember != Member)
3708  NonTemplateMember->setAccess(AS);
3709 
3710  // C++ [temp.deduct.guide]p3:
3711  // A deduction guide [...] for a member class template [shall be
3712  // declared] with the same access [as the template].
3713  if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3714  auto *TD = DG->getDeducedTemplate();
3715  // Access specifiers are only meaningful if both the template and the
3716  // deduction guide are from the same scope.
3717  if (AS != TD->getAccess() &&
3718  TD->getDeclContext()->getRedeclContext()->Equals(
3719  DG->getDeclContext()->getRedeclContext())) {
3720  Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3721  Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3722  << TD->getAccess();
3723  const AccessSpecDecl *LastAccessSpec = nullptr;
3724  for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3725  if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3726  LastAccessSpec = AccessSpec;
3727  }
3728  assert(LastAccessSpec && "differing access with no access specifier");
3729  Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3730  << AS;
3731  }
3732  }
3733  }
3734 
3735  if (VS.isOverrideSpecified())
3736  Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));
3737  if (VS.isFinalSpecified())
3738  Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),
3740  ? FinalAttr::Keyword_sealed
3741  : FinalAttr::Keyword_final));
3742 
3743  if (VS.getLastLocation().isValid()) {
3744  // Update the end location of a method that has a virt-specifiers.
3745  if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3746  MD->setRangeEnd(VS.getLastLocation());
3747  }
3748 
3750 
3751  assert((Name || isInstField) && "No identifier for non-field ?");
3752 
3753  if (isInstField) {
3754  FieldDecl *FD = cast<FieldDecl>(Member);
3755  FieldCollector->Add(FD);
3756 
3757  if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3758  // Remember all explicit private FieldDecls that have a name, no side
3759  // effects and are not part of a dependent type declaration.
3760 
3761  auto DeclHasUnusedAttr = [](const QualType &T) {
3762  if (const TagDecl *TD = T->getAsTagDecl())
3763  return TD->hasAttr<UnusedAttr>();
3764  if (const TypedefType *TDT = T->getAs<TypedefType>())
3765  return TDT->getDecl()->hasAttr<UnusedAttr>();
3766  return false;
3767  };
3768 
3769  if (!FD->isImplicit() && FD->getDeclName() &&
3770  FD->getAccess() == AS_private &&
3771  !FD->hasAttr<UnusedAttr>() &&
3772  !FD->getParent()->isDependentContext() &&
3773  !DeclHasUnusedAttr(FD->getType()) &&
3775  UnusedPrivateFields.insert(FD);
3776  }
3777  }
3778 
3779  // Emit diagnostic if a private member of type decorated with device_global
3780  // attribute is accessed.
3781  if (getLangOpts().SYCLIsDevice) {
3782  if (auto Value = dyn_cast<ValueDecl>(Member)) {
3783  if (SYCL().isTypeDecoratedWithDeclAttribute<SYCLDeviceGlobalAttr>(
3784  Value->getType())) {
3785  if (Value->getAccess() == AS_private ||
3786  Value->getAccess() == AS_protected) {
3787  Diag(Loc, diag::err_sycl_device_global_not_publicly_accessible)
3788  << Value;
3789  }
3790  const DeclContext *DC = Member->getDeclContext();
3791  while (!DC->isTranslationUnit()) {
3792  if (auto Decl = dyn_cast<NamedDecl>(DC)) {
3793  if (Decl->getAccess() == AS_private ||
3794  Decl->getAccess() == AS_protected) {
3795  Diag(Loc, diag::err_sycl_device_global_not_publicly_accessible)
3796  << Value;
3797  break;
3798  }
3799  }
3800  DC = DC->getParent();
3801  }
3802  }
3803  }
3804  }
3805 
3806  return Member;
3807 }
3808 
3809 namespace {
3810  class UninitializedFieldVisitor
3811  : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3812  Sema &S;
3813  // List of Decls to generate a warning on. Also remove Decls that become
3814  // initialized.
3815  llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3816  // List of base classes of the record. Classes are removed after their
3817  // initializers.
3818  llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3819  // Vector of decls to be removed from the Decl set prior to visiting the
3820  // nodes. These Decls may have been initialized in the prior initializer.
3821  llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3822  // If non-null, add a note to the warning pointing back to the constructor.
3823  const CXXConstructorDecl *Constructor;
3824  // Variables to hold state when processing an initializer list. When
3825  // InitList is true, special case initialization of FieldDecls matching
3826  // InitListFieldDecl.
3827  bool InitList;
3828  FieldDecl *InitListFieldDecl;
3829  llvm::SmallVector<unsigned, 4> InitFieldIndex;
3830 
3831  public:
3833  UninitializedFieldVisitor(Sema &S,
3834  llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3835  llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3836  : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3837  Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3838 
3839  // Returns true if the use of ME is not an uninitialized use.
3840  bool IsInitListMemberExprInitialized(MemberExpr *ME,
3841  bool CheckReferenceOnly) {
3843  bool ReferenceField = false;
3844  while (ME) {
3845  FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3846  if (!FD)
3847  return false;
3848  Fields.push_back(FD);
3849  if (FD->getType()->isReferenceType())
3850  ReferenceField = true;
3851  ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3852  }
3853 
3854  // Binding a reference to an uninitialized field is not an
3855  // uninitialized use.
3856  if (CheckReferenceOnly && !ReferenceField)
3857  return true;
3858 
3859  llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3860  // Discard the first field since it is the field decl that is being
3861  // initialized.
3862  for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3863  UsedFieldIndex.push_back(FD->getFieldIndex());
3864 
3865  for (auto UsedIter = UsedFieldIndex.begin(),
3866  UsedEnd = UsedFieldIndex.end(),
3867  OrigIter = InitFieldIndex.begin(),
3868  OrigEnd = InitFieldIndex.end();
3869  UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3870  if (*UsedIter < *OrigIter)
3871  return true;
3872  if (*UsedIter > *OrigIter)
3873  break;
3874  }
3875 
3876  return false;
3877  }
3878 
3879  void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3880  bool AddressOf) {
3881  if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3882  return;
3883 
3884  // FieldME is the inner-most MemberExpr that is not an anonymous struct
3885  // or union.
3886  MemberExpr *FieldME = ME;
3887 
3888  bool AllPODFields = FieldME->getType().isPODType(S.Context);
3889 
3890  Expr *Base = ME;
3891  while (MemberExpr *SubME =
3892  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3893 
3894  if (isa<VarDecl>(SubME->getMemberDecl()))
3895  return;
3896 
3897  if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3898  if (!FD->isAnonymousStructOrUnion())
3899  FieldME = SubME;
3900 
3901  if (!FieldME->getType().isPODType(S.Context))
3902  AllPODFields = false;
3903 
3904  Base = SubME->getBase();
3905  }
3906 
3907  if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3908  Visit(Base);
3909  return;
3910  }
3911 
3912  if (AddressOf && AllPODFields)
3913  return;
3914 
3915  ValueDecl* FoundVD = FieldME->getMemberDecl();
3916 
3917  if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3918  while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3919  BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3920  }
3921 
3922  if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3923  QualType T = BaseCast->getType();
3924  if (T->isPointerType() &&
3925  BaseClasses.count(T->getPointeeType())) {
3926  S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3927  << T->getPointeeType() << FoundVD;
3928  }
3929  }
3930  }
3931 
3932  if (!Decls.count(FoundVD))
3933  return;
3934 
3935  const bool IsReference = FoundVD->getType()->isReferenceType();
3936 
3937  if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3938  // Special checking for initializer lists.
3939  if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3940  return;
3941  }
3942  } else {
3943  // Prevent double warnings on use of unbounded references.
3944  if (CheckReferenceOnly && !IsReference)
3945  return;
3946  }
3947 
3948  unsigned diag = IsReference
3949  ? diag::warn_reference_field_is_uninit
3950  : diag::warn_field_is_uninit;
3951  S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3952  if (Constructor)
3953  S.Diag(Constructor->getLocation(),
3954  diag::note_uninit_in_this_constructor)
3955  << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3956 
3957  }
3958 
3959  void HandleValue(Expr *E, bool AddressOf) {
3960  E = E->IgnoreParens();
3961 
3962  if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3963  HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3964  AddressOf /*AddressOf*/);
3965  return;
3966  }
3967 
3968  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3969  Visit(CO->getCond());
3970  HandleValue(CO->getTrueExpr(), AddressOf);
3971  HandleValue(CO->getFalseExpr(), AddressOf);
3972  return;
3973  }
3974 
3975  if (BinaryConditionalOperator *BCO =
3976  dyn_cast<BinaryConditionalOperator>(E)) {
3977  Visit(BCO->getCond());
3978  HandleValue(BCO->getFalseExpr(), AddressOf);
3979  return;
3980  }
3981 
3982  if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3983  HandleValue(OVE->getSourceExpr(), AddressOf);
3984  return;
3985  }
3986 
3987  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3988  switch (BO->getOpcode()) {
3989  default:
3990  break;
3991  case(BO_PtrMemD):
3992  case(BO_PtrMemI):
3993  HandleValue(BO->getLHS(), AddressOf);
3994  Visit(BO->getRHS());
3995  return;
3996  case(BO_Comma):
3997  Visit(BO->getLHS());
3998  HandleValue(BO->getRHS(), AddressOf);
3999  return;
4000  }
4001  }
4002 
4003  Visit(E);
4004  }
4005 
4006  void CheckInitListExpr(InitListExpr *ILE) {
4007  InitFieldIndex.push_back(0);
4008  for (auto *Child : ILE->children()) {
4009  if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
4010  CheckInitListExpr(SubList);
4011  } else {
4012  Visit(Child);
4013  }
4014  ++InitFieldIndex.back();
4015  }
4016  InitFieldIndex.pop_back();
4017  }
4018 
4019  void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
4020  FieldDecl *Field, const Type *BaseClass) {
4021  // Remove Decls that may have been initialized in the previous
4022  // initializer.
4023  for (ValueDecl* VD : DeclsToRemove)
4024  Decls.erase(VD);
4025  DeclsToRemove.clear();
4026 
4027  Constructor = FieldConstructor;
4028  InitListExpr *ILE = dyn_cast<InitListExpr>(E);
4029 
4030  if (ILE && Field) {
4031  InitList = true;
4032  InitListFieldDecl = Field;
4033  InitFieldIndex.clear();
4034  CheckInitListExpr(ILE);
4035  } else {
4036  InitList = false;
4037  Visit(E);
4038  }
4039 
4040  if (Field)
4041  Decls.erase(Field);
4042  if (BaseClass)
4043  BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
4044  }
4045 
4046  void VisitMemberExpr(MemberExpr *ME) {
4047  // All uses of unbounded reference fields will warn.
4048  HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
4049  }
4050 
4051  void VisitImplicitCastExpr(ImplicitCastExpr *E) {
4052  if (E->getCastKind() == CK_LValueToRValue) {
4053  HandleValue(E->getSubExpr(), false /*AddressOf*/);
4054  return;
4055  }
4056 
4057  Inherited::VisitImplicitCastExpr(E);
4058  }
4059 
4060  void VisitCXXConstructExpr(CXXConstructExpr *E) {
4061  if (E->getConstructor()->isCopyConstructor()) {
4062  Expr *ArgExpr = E->getArg(0);
4063  if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
4064  if (ILE->getNumInits() == 1)
4065  ArgExpr = ILE->getInit(0);
4066  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
4067  if (ICE->getCastKind() == CK_NoOp)
4068  ArgExpr = ICE->getSubExpr();
4069  HandleValue(ArgExpr, false /*AddressOf*/);
4070  return;
4071  }
4072  Inherited::VisitCXXConstructExpr(E);
4073  }
4074 
4075  void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4076  Expr *Callee = E->getCallee();
4077  if (isa<MemberExpr>(Callee)) {
4078  HandleValue(Callee, false /*AddressOf*/);
4079  for (auto *Arg : E->arguments())
4080  Visit(Arg);
4081  return;
4082  }
4083 
4084  Inherited::VisitCXXMemberCallExpr(E);
4085  }
4086 
4087  void VisitCallExpr(CallExpr *E) {
4088  // Treat std::move as a use.
4089  if (E->isCallToStdMove()) {
4090  HandleValue(E->getArg(0), /*AddressOf=*/false);
4091  return;
4092  }
4093 
4094  Inherited::VisitCallExpr(E);
4095  }
4096 
4097  void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4098  Expr *Callee = E->getCallee();
4099 
4100  if (isa<UnresolvedLookupExpr>(Callee))
4101  return Inherited::VisitCXXOperatorCallExpr(E);
4102 
4103  Visit(Callee);
4104  for (auto *Arg : E->arguments())
4105  HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
4106  }
4107 
4108  void VisitBinaryOperator(BinaryOperator *E) {
4109  // If a field assignment is detected, remove the field from the
4110  // uninitiailized field set.
4111  if (E->getOpcode() == BO_Assign)
4112  if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
4113  if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
4114  if (!FD->getType()->isReferenceType())
4115  DeclsToRemove.push_back(FD);
4116 
4117  if (E->isCompoundAssignmentOp()) {
4118  HandleValue(E->getLHS(), false /*AddressOf*/);
4119  Visit(E->getRHS());
4120  return;
4121  }
4122 
4123  Inherited::VisitBinaryOperator(E);
4124  }
4125 
4126  void VisitUnaryOperator(UnaryOperator *E) {
4127  if (E->isIncrementDecrementOp()) {
4128  HandleValue(E->getSubExpr(), false /*AddressOf*/);
4129  return;
4130  }
4131  if (E->getOpcode() == UO_AddrOf) {
4132  if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
4133  HandleValue(ME->getBase(), true /*AddressOf*/);
4134  return;
4135  }
4136  }
4137 
4138  Inherited::VisitUnaryOperator(E);
4139  }
4140  };
4141 
4142  // Diagnose value-uses of fields to initialize themselves, e.g.
4143  // foo(foo)
4144  // where foo is not also a parameter to the constructor.
4145  // Also diagnose across field uninitialized use such as
4146  // x(y), y(x)
4147  // TODO: implement -Wuninitialized and fold this into that framework.
4148  static void DiagnoseUninitializedFields(
4149  Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4150 
4151  if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
4152  Constructor->getLocation())) {
4153  return;
4154  }
4155 
4156  if (Constructor->isInvalidDecl())
4157  return;
4158 
4159  const CXXRecordDecl *RD = Constructor->getParent();
4160 
4161  if (RD->isDependentContext())
4162  return;
4163 
4164  // Holds fields that are uninitialized.
4165  llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4166 
4167  // At the beginning, all fields are uninitialized.
4168  for (auto *I : RD->decls()) {
4169  if (auto *FD = dyn_cast<FieldDecl>(I)) {
4170  UninitializedFields.insert(FD);
4171  } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
4172  UninitializedFields.insert(IFD->getAnonField());
4173  }
4174  }
4175 
4176  llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4177  for (const auto &I : RD->bases())
4178  UninitializedBaseClasses.insert(I.getType().getCanonicalType());
4179 
4180  if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4181  return;
4182 
4183  UninitializedFieldVisitor UninitializedChecker(SemaRef,
4184  UninitializedFields,
4185  UninitializedBaseClasses);
4186 
4187  for (const auto *FieldInit : Constructor->inits()) {
4188  if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4189  break;
4190 
4191  Expr *InitExpr = FieldInit->getInit();
4192  if (!InitExpr)
4193  continue;
4194 
4195  if (CXXDefaultInitExpr *Default =
4196  dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
4197  InitExpr = Default->getExpr();
4198  if (!InitExpr)
4199  continue;
4200  // In class initializers will point to the constructor.
4201  UninitializedChecker.CheckInitializer(InitExpr, Constructor,
4202  FieldInit->getAnyMember(),
4203  FieldInit->getBaseClass());
4204  } else {
4205  UninitializedChecker.CheckInitializer(InitExpr, nullptr,
4206  FieldInit->getAnyMember(),
4207  FieldInit->getBaseClass());
4208  }
4209  }
4210  }
4211 } // namespace
4212 
4213 /// Enter a new C++ default initializer scope. After calling this, the
4214 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
4215 /// parsing or instantiating the initializer failed.
4217  // Create a synthetic function scope to represent the call to the constructor
4218  // that notionally surrounds a use of this initializer.
4220 }
4221 
4223  if (!D.isFunctionDeclarator())
4224  return;
4225  auto &FTI = D.getFunctionTypeInfo();
4226  if (!FTI.Params)
4227  return;
4228  for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4229  FTI.NumParams)) {
4230  auto *ParamDecl = cast<NamedDecl>(Param.Param);
4231  if (ParamDecl->getDeclName())
4232  PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4233  }
4234 }
4235 
4237  return ActOnRequiresClause(ConstraintExpr);
4238 }
4239 
4241  if (ConstraintExpr.isInvalid())
4242  return ExprError();
4243 
4244  ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
4245  if (ConstraintExpr.isInvalid())
4246  return ExprError();
4247 
4248  if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4250  return ExprError();
4251 
4252  return ConstraintExpr;
4253 }
4254 
4256  Expr *InitExpr,
4257  SourceLocation InitLoc) {
4258  InitializedEntity Entity =
4263  InitExpr->getBeginLoc(),
4264  InitExpr->getEndLoc())
4265  : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4266  InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4267  return Seq.Perform(*this, Entity, Kind, InitExpr);
4268 }
4269 
4270 /// This is invoked after parsing an in-class initializer for a
4271 /// non-static C++ class member, and after instantiating an in-class initializer
4272 /// in a class template. Such actions are deferred until the class is complete.
4274  SourceLocation InitLoc,
4275  Expr *InitExpr) {
4276  // Pop the notional constructor scope we created earlier.
4277  PopFunctionScopeInfo(nullptr, D);
4278 
4279  FieldDecl *FD = dyn_cast<FieldDecl>(D);
4280  assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
4281  "must set init style when field is created");
4282 
4283  if (!InitExpr) {
4284  D->setInvalidDecl();
4285  if (FD)
4287  return;
4288  }
4289 
4291  FD->setInvalidDecl();
4293  return;
4294  }
4295 
4296  ExprResult Init = CorrectDelayedTyposInExpr(InitExpr, /*InitDecl=*/nullptr,
4297  /*RecoverUncorrectedTypos=*/true);
4298  assert(Init.isUsable() && "Init should at least have a RecoveryExpr");
4299  if (!FD->getType()->isDependentType() && !Init.get()->isTypeDependent()) {
4300  Init = ConvertMemberDefaultInitExpression(FD, Init.get(), InitLoc);
4301  // C++11 [class.base.init]p7:
4302  // The initialization of each base and member constitutes a
4303  // full-expression.
4304  if (!Init.isInvalid())
4305  Init = ActOnFinishFullExpr(Init.get(), /*DiscarededValue=*/false);
4306  if (Init.isInvalid()) {
4307  FD->setInvalidDecl();
4308  return;
4309  }
4310  }
4311 
4312  FD->setInClassInitializer(Init.get());
4313 }
4314 
4315 /// Find the direct and/or virtual base specifiers that
4316 /// correspond to the given base type, for use in base initialization
4317 /// within a constructor.
4319  CXXRecordDecl *ClassDecl,
4320  QualType BaseType,
4321  const CXXBaseSpecifier *&DirectBaseSpec,
4322  const CXXBaseSpecifier *&VirtualBaseSpec) {
4323  // First, check for a direct base class.
4324  DirectBaseSpec = nullptr;
4325  for (const auto &Base : ClassDecl->bases()) {
4326  if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4327  // We found a direct base of this type. That's what we're
4328  // initializing.
4329  DirectBaseSpec = &Base;
4330  break;
4331  }
4332  }
4333 
4334  // Check for a virtual base class.
4335  // FIXME: We might be able to short-circuit this if we know in advance that
4336  // there are no virtual bases.
4337  VirtualBaseSpec = nullptr;
4338  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4339  // We haven't found a base yet; search the class hierarchy for a
4340  // virtual base class.
4341  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4342  /*DetectVirtual=*/false);
4343  if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4344  SemaRef.Context.getTypeDeclType(ClassDecl),
4345  BaseType, Paths)) {
4346  for (CXXBasePaths::paths_iterator Path = Paths.begin();
4347  Path != Paths.end(); ++Path) {
4348  if (Path->back().Base->isVirtual()) {
4349  VirtualBaseSpec = Path->back().Base;
4350  break;
4351  }
4352  }
4353  }
4354  }
4355 
4356  return DirectBaseSpec || VirtualBaseSpec;
4357 }
4358 
4359 /// Handle a C++ member initializer using braced-init-list syntax.
4362  Scope *S,
4363  CXXScopeSpec &SS,
4364  IdentifierInfo *MemberOrBase,
4365  ParsedType TemplateTypeTy,
4366  const DeclSpec &DS,
4367  SourceLocation IdLoc,
4368  Expr *InitList,
4369  SourceLocation EllipsisLoc) {
4370  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4371  DS, IdLoc, InitList,
4372  EllipsisLoc);
4373 }
4374 
4375 /// Handle a C++ member initializer using parentheses syntax.
4378  Scope *S,
4379  CXXScopeSpec &SS,
4380  IdentifierInfo *MemberOrBase,
4381  ParsedType TemplateTypeTy,
4382  const DeclSpec &DS,
4383  SourceLocation IdLoc,
4384  SourceLocation LParenLoc,
4385  ArrayRef<Expr *> Args,
4386  SourceLocation RParenLoc,
4387  SourceLocation EllipsisLoc) {
4388  Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4389  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4390  DS, IdLoc, List, EllipsisLoc);
4391 }
4392 
4393 namespace {
4394 
4395 // Callback to only accept typo corrections that can be a valid C++ member
4396 // initializer: either a non-static field member or a base class.
4397 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4398 public:
4399  explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4400  : ClassDecl(ClassDecl) {}
4401 
4402  bool ValidateCandidate(const TypoCorrection &candidate) override {
4403  if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4404  if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4405  return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4406  return isa<TypeDecl>(ND);
4407  }
4408  return false;
4409  }
4410 
4411  std::unique_ptr<CorrectionCandidateCallback> clone() override {
4412  return std::make_unique<MemInitializerValidatorCCC>(*this);
4413  }
4414 
4415 private:
4416  CXXRecordDecl *ClassDecl;
4417 };
4418 
4419 }
4420 
4422  RecordDecl *ClassDecl,
4423  const IdentifierInfo *Name) {
4424  DeclContextLookupResult Result = ClassDecl->lookup(Name);
4426  llvm::find_if(Result, [this](const NamedDecl *Elem) {
4427  return isa<FieldDecl, IndirectFieldDecl>(Elem) &&
4428  Elem->isPlaceholderVar(getLangOpts());
4429  });
4430  // We did not find a placeholder variable
4431  if (Found == Result.end())
4432  return false;
4433  Diag(Loc, diag::err_using_placeholder_variable) << Name;
4434  for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4435  const NamedDecl *ND = *It;
4436  if (ND->getDeclContext() != ND->getDeclContext())
4437  break;
4438  if (isa<FieldDecl, IndirectFieldDecl>(ND) &&
4440  Diag(ND->getLocation(), diag::note_reference_placeholder) << ND;
4441  }
4442  return true;
4443 }
4444 
4445 ValueDecl *
4447  const IdentifierInfo *MemberOrBase) {
4448  ValueDecl *ND = nullptr;
4449  for (auto *D : ClassDecl->lookup(MemberOrBase)) {
4450  if (isa<FieldDecl, IndirectFieldDecl>(D)) {
4451  bool IsPlaceholder = D->isPlaceholderVar(getLangOpts());
4452  if (ND) {
4453  if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4454  return nullptr;
4455  break;
4456  }
4457  if (!IsPlaceholder)
4458  return cast<ValueDecl>(D);
4459  ND = cast<ValueDecl>(D);
4460  }
4461  }
4462  return ND;
4463 }
4464 
4465 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4466  CXXScopeSpec &SS,
4467  ParsedType TemplateTypeTy,
4468  IdentifierInfo *MemberOrBase) {
4469  if (SS.getScopeRep() || TemplateTypeTy)
4470  return nullptr;
4471  return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4472 }
4473 
4474 /// Handle a C++ member initializer.
4477  Scope *S,
4478  CXXScopeSpec &SS,
4479  IdentifierInfo *MemberOrBase,
4480  ParsedType TemplateTypeTy,
4481  const DeclSpec &DS,
4482  SourceLocation IdLoc,
4483  Expr *Init,
4484  SourceLocation EllipsisLoc) {
4485  ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
4486  /*RecoverUncorrectedTypos=*/true);
4487  if (!Res.isUsable())
4488  return true;
4489  Init = Res.get();
4490 
4491  if (!ConstructorD)
4492  return true;
4493 
4494  AdjustDeclIfTemplate(ConstructorD);
4495 
4496  CXXConstructorDecl *Constructor
4497  = dyn_cast<CXXConstructorDecl>(ConstructorD);
4498  if (!Constructor) {
4499  // The user wrote a constructor initializer on a function that is
4500  // not a C++ constructor. Ignore the error for now, because we may
4501  // have more member initializers coming; we'll diagnose it just
4502  // once in ActOnMemInitializers.
4503  return true;
4504  }
4505 
4506  CXXRecordDecl *ClassDecl = Constructor->getParent();
4507 
4508  // C++ [class.base.init]p2:
4509  // Names in a mem-initializer-id are looked up in the scope of the
4510  // constructor's class and, if not found in that scope, are looked
4511  // up in the scope containing the constructor's definition.
4512  // [Note: if the constructor's class contains a member with the
4513  // same name as a direct or virtual base class of the class, a
4514  // mem-initializer-id naming the member or base class and composed
4515  // of a single identifier refers to the class member. A
4516  // mem-initializer-id for the hidden base class may be specified
4517  // using a qualified name. ]
4518 
4519  // Look for a member, first.
4520  if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4521  ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4522  if (EllipsisLoc.isValid())
4523  Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4524  << MemberOrBase
4525  << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4526 
4527  return BuildMemberInitializer(Member, Init, IdLoc);
4528  }
4529  // It didn't name a member, so see if it names a class.
4530  QualType BaseType;
4531  TypeSourceInfo *TInfo = nullptr;
4532 
4533  if (TemplateTypeTy) {
4534  BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4535  if (BaseType.isNull())
4536  return true;
4537  } else if (DS.getTypeSpecType() == TST_decltype) {
4538  BaseType = BuildDecltypeType(DS.getRepAsExpr());
4539  } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4540  Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4541  return true;
4542  } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4543  BaseType =
4545  DS.getBeginLoc(), DS.getEllipsisLoc());
4546  } else {
4547  LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4548  LookupParsedName(R, S, &SS);
4549 
4550  TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4551  if (!TyD) {
4552  if (R.isAmbiguous()) return true;
4553 
4554  // We don't want access-control diagnostics here.
4555  R.suppressDiagnostics();
4556 
4557  if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4558  bool NotUnknownSpecialization = false;
4559  DeclContext *DC = computeDeclContext(SS, false);
4560  if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4561  NotUnknownSpecialization = !Record->hasAnyDependentBases();
4562 
4563  if (!NotUnknownSpecialization) {
4564  // When the scope specifier can refer to a member of an unknown
4565  // specialization, we take it as a type name.
4566  BaseType = CheckTypenameType(
4568  SS.getWithLocInContext(Context), *MemberOrBase, IdLoc);
4569  if (BaseType.isNull())
4570  return true;
4571 
4572  TInfo = Context.CreateTypeSourceInfo(BaseType);
4575  if (!TL.isNull()) {
4576  TL.setNameLoc(IdLoc);
4579  }
4580 
4581  R.clear();
4582  R.setLookupName(MemberOrBase);
4583  }
4584  }
4585 
4586  if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4587  if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4588  auto *TempSpec = cast<TemplateSpecializationType>(
4589  UnqualifiedBase->getInjectedClassNameSpecialization());
4590  TemplateName TN = TempSpec->getTemplateName();
4591  for (auto const &Base : ClassDecl->bases()) {
4592  auto BaseTemplate =
4593  Base.getType()->getAs<TemplateSpecializationType>();
4594  if (BaseTemplate && Context.hasSameTemplateName(
4595  BaseTemplate->getTemplateName(), TN)) {
4596  Diag(IdLoc, diag::ext_unqualified_base_class)
4597  << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4598  BaseType = Base.getType();
4599  break;
4600  }
4601  }
4602  }
4603  }
4604 
4605  // If no results were found, try to correct typos.
4606  TypoCorrection Corr;
4607  MemInitializerValidatorCCC CCC(ClassDecl);
4608  if (R.empty() && BaseType.isNull() &&
4609  (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4610  CCC, CTK_ErrorRecovery, ClassDecl))) {
4611  if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4612  // We have found a non-static data member with a similar
4613  // name to what was typed; complain and initialize that
4614  // member.
4615  diagnoseTypo(Corr,
4616  PDiag(diag::err_mem_init_not_member_or_class_suggest)
4617  << MemberOrBase << true);
4618  return BuildMemberInitializer(Member, Init, IdLoc);
4619  } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4620  const CXXBaseSpecifier *DirectBaseSpec;
4621  const CXXBaseSpecifier *VirtualBaseSpec;
4622  if (FindBaseInitializer(*this, ClassDecl,
4624  DirectBaseSpec, VirtualBaseSpec)) {
4625  // We have found a direct or virtual base class with a
4626  // similar name to what was typed; complain and initialize
4627  // that base class.
4628  diagnoseTypo(Corr,
4629  PDiag(diag::err_mem_init_not_member_or_class_suggest)
4630  << MemberOrBase << false,
4631  PDiag() /*Suppress note, we provide our own.*/);
4632 
4633  const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4634  : VirtualBaseSpec;
4635  Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4636  << BaseSpec->getType() << BaseSpec->getSourceRange();
4637 
4638  TyD = Type;
4639  }
4640  }
4641  }
4642 
4643  if (!TyD && BaseType.isNull()) {
4644  Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4645  << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4646  return true;
4647  }
4648  }
4649 
4650  if (BaseType.isNull()) {
4652  Context.getTypeDeclType(TyD));
4653  MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4654  TInfo = Context.CreateTypeSourceInfo(BaseType);
4656  TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4659  }
4660  }
4661 
4662  if (!TInfo)
4663  TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4664 
4665  return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4666 }
4667 
4670  SourceLocation IdLoc) {
4671  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4672  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4673  assert((DirectMember || IndirectMember) &&
4674  "Member must be a FieldDecl or IndirectFieldDecl");
4675 
4677  return true;
4678 
4679  if (Member->isInvalidDecl())
4680  return true;
4681 
4682  MultiExprArg Args;
4683  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4684  Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4685  } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4686  Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4687  } else {
4688  // Template instantiation doesn't reconstruct ParenListExprs for us.
4689  Args = Init;
4690  }
4691 
4692  SourceRange InitRange = Init->getSourceRange();
4693 
4694  if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4695  // Can't check initialization for a member of dependent type or when
4696  // any of the arguments are type-dependent expressions.
4698  } else {
4699  bool InitList = false;
4700  if (isa<InitListExpr>(Init)) {
4701  InitList = true;
4702  Args = Init;
4703  }
4704 
4705  // Initialize the member.
4706  InitializedEntity MemberEntity =
4707  DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4708  : InitializedEntity::InitializeMember(IndirectMember,
4709  nullptr);
4712  IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4713  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4714  InitRange.getEnd());
4715 
4716  InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4717  ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4718  nullptr);
4719  if (!MemberInit.isInvalid()) {
4720  // C++11 [class.base.init]p7:
4721  // The initialization of each base and member constitutes a
4722  // full-expression.
4723  MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4724  /*DiscardedValue*/ false);
4725  }
4726 
4727  if (MemberInit.isInvalid()) {
4728  // Args were sensible expressions but we couldn't initialize the member
4729  // from them. Preserve them in a RecoveryExpr instead.
4730  Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4731  Member->getType())
4732  .get();
4733  if (!Init)
4734  return true;
4735  } else {
4736  Init = MemberInit.get();
4737  }
4738  }
4739 
4740  if (DirectMember) {
4741  return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4742  InitRange.getBegin(), Init,
4743  InitRange.getEnd());
4744  } else {
4745  return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4746  InitRange.getBegin(), Init,
4747  InitRange.getEnd());
4748  }
4749 }
4750 
4753  CXXRecordDecl *ClassDecl) {
4754  SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4755  if (!LangOpts.CPlusPlus11)
4756  return Diag(NameLoc, diag::err_delegating_ctor)
4757  << TInfo->getTypeLoc().getSourceRange();
4758  Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4759 
4760  bool InitList = true;
4761  MultiExprArg Args = Init;
4762  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4763  InitList = false;
4764  Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4765  }
4766 
4767  SourceRange InitRange = Init->getSourceRange();
4768  // Initialize the object.
4770  QualType(ClassDecl->getTypeForDecl(), 0));
4773  NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4774  : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4775  InitRange.getEnd());
4776  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4777  ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4778  Args, nullptr);
4779  if (!DelegationInit.isInvalid()) {
4780  assert((DelegationInit.get()->containsErrors() ||
4781  cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4782  "Delegating constructor with no target?");
4783 
4784  // C++11 [class.base.init]p7:
4785  // The initialization of each base and member constitutes a
4786  // full-expression.
4787  DelegationInit = ActOnFinishFullExpr(
4788  DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4789  }
4790 
4791  if (DelegationInit.isInvalid()) {
4792  DelegationInit =
4793  CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4794  QualType(ClassDecl->getTypeForDecl(), 0));
4795  if (DelegationInit.isInvalid())
4796  return true;
4797  } else {
4798  // If we are in a dependent context, template instantiation will
4799  // perform this type-checking again. Just save the arguments that we
4800  // received in a ParenListExpr.
4801  // FIXME: This isn't quite ideal, since our ASTs don't capture all
4802  // of the information that we have about the base
4803  // initializer. However, deconstructing the ASTs is a dicey process,
4804  // and this approach is far more likely to get the corner cases right.
4806  DelegationInit = Init;
4807  }
4808 
4809  return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4810  DelegationInit.getAs<Expr>(),
4811  InitRange.getEnd());
4812 }
4813 
4816  Expr *Init, CXXRecordDecl *ClassDecl,
4817  SourceLocation EllipsisLoc) {
4818  SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4819 
4820  if (!BaseType->isDependentType() && !BaseType->isRecordType())
4821  return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4822  << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4823 
4824  // C++ [class.base.init]p2:
4825  // [...] Unless the mem-initializer-id names a nonstatic data
4826  // member of the constructor's class or a direct or virtual base
4827  // of that class, the mem-initializer is ill-formed. A
4828  // mem-initializer-list can initialize a base class using any
4829  // name that denotes that base class type.
4830 
4831  // We can store the initializers in "as-written" form and delay analysis until
4832  // instantiation if the constructor is dependent. But not for dependent
4833  // (broken) code in a non-template! SetCtorInitializers does not expect this.
4834  bool Dependent = CurContext->isDependentContext() &&
4835  (BaseType->isDependentType() || Init->isTypeDependent());
4836 
4837  SourceRange InitRange = Init->getSourceRange();
4838  if (EllipsisLoc.isValid()) {
4839  // This is a pack expansion.
4840  if (!BaseType->containsUnexpandedParameterPack()) {
4841  Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4842  << SourceRange(BaseLoc, InitRange.getEnd());
4843 
4844  EllipsisLoc = SourceLocation();
4845  }
4846  } else {
4847  // Check for any unexpanded parameter packs.
4848  if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4849  return true;
4850 
4852  return true;
4853  }
4854 
4855  // Check for direct and virtual base classes.
4856  const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4857  const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4858  if (!Dependent) {
4860  BaseType))
4861  return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4862 
4863  FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4864  VirtualBaseSpec);
4865 
4866  // C++ [base.class.init]p2:
4867  // Unless the mem-initializer-id names a nonstatic data member of the
4868  // constructor's class or a direct or virtual base of that class, the
4869  // mem-initializer is ill-formed.
4870  if (!DirectBaseSpec && !VirtualBaseSpec) {
4871  // If the class has any dependent bases, then it's possible that
4872  // one of those types will resolve to the same type as
4873  // BaseType. Therefore, just treat this as a dependent base
4874  // class initialization. FIXME: Should we try to check the
4875  // initialization anyway? It seems odd.
4876  if (ClassDecl->hasAnyDependentBases())
4877  Dependent = true;
4878  else
4879  return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4880  << BaseType << Context.getTypeDeclType(ClassDecl)
4881  << BaseTInfo->getTypeLoc().getSourceRange();
4882  }
4883  }
4884 
4885  if (Dependent) {
4887 
4888  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4889  /*IsVirtual=*/false,
4890  InitRange.getBegin(), Init,
4891  InitRange.getEnd(), EllipsisLoc);
4892  }
4893 
4894  // C++ [base.class.init]p2:
4895  // If a mem-initializer-id is ambiguous because it designates both
4896  // a direct non-virtual base class and an inherited virtual base
4897  // class, the mem-initializer is ill-formed.
4898  if (DirectBaseSpec && VirtualBaseSpec)
4899  return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4900  << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4901 
4902  const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4903  if (!BaseSpec)
4904  BaseSpec = VirtualBaseSpec;
4905 
4906  // Initialize the base.
4907  bool InitList = true;
4908  MultiExprArg Args = Init;
4909  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4910  InitList = false;
4911  Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4912  }
4913 
4914  InitializedEntity BaseEntity =
4915  InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4917  InitList ? InitializationKind::CreateDirectList(BaseLoc)
4918  : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4919  InitRange.getEnd());
4920  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4921  ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4922  if (!BaseInit.isInvalid()) {
4923  // C++11 [class.base.init]p7:
4924  // The initialization of each base and member constitutes a
4925  // full-expression.
4926  BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4927  /*DiscardedValue*/ false);
4928  }
4929 
4930  if (BaseInit.isInvalid()) {
4931  BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4932  Args, BaseType);
4933  if (BaseInit.isInvalid())
4934  return true;
4935  } else {
4936  // If we are in a dependent context, template instantiation will
4937  // perform this type-checking again. Just save the arguments that we
4938  // received in a ParenListExpr.
4939  // FIXME: This isn't quite ideal, since our ASTs don't capture all
4940  // of the information that we have about the base
4941  // initializer. However, deconstructing the ASTs is a dicey process,
4942  // and this approach is far more likely to get the corner cases right.
4944  BaseInit = Init;
4945  }
4946 
4947  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4948  BaseSpec->isVirtual(),
4949  InitRange.getBegin(),
4950  BaseInit.getAs<Expr>(),
4951  InitRange.getEnd(), EllipsisLoc);
4952 }
4953 
4954 // Create a static_cast<T&&>(expr).
4956  QualType TargetType =
4957  SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
4959  SourceLocation ExprLoc = E->getBeginLoc();
4961  TargetType, ExprLoc);
4962 
4963  return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4964  SourceRange(ExprLoc, ExprLoc),
4965  E->getSourceRange()).get();
4966 }
4967 
4968 /// ImplicitInitializerKind - How an implicit base or member initializer should
4969 /// initialize its base or member.
4974  IIK_Inherit
4975 };
4976 
4977 static bool
4979  ImplicitInitializerKind ImplicitInitKind,
4980  CXXBaseSpecifier *BaseSpec,
4981  bool IsInheritedVirtualBase,
4982  CXXCtorInitializer *&CXXBaseInit) {
4983  InitializedEntity InitEntity
4985  IsInheritedVirtualBase);
4986 
4987  ExprResult BaseInit;
4988 
4989  switch (ImplicitInitKind) {
4990  case IIK_Inherit:
4991  case IIK_Default: {
4992  InitializationKind InitKind
4993  = InitializationKind::CreateDefault(Constructor->getLocation());
4994  InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
4995  BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);
4996  break;
4997  }
4998 
4999  case IIK_Move:
5000  case IIK_Copy: {
5001  bool Moving = ImplicitInitKind == IIK_Move;
5002  ParmVarDecl *Param = Constructor->getParamDecl(0);
5003  QualType ParamType = Param->getType().getNonReferenceType();
5004 
5005  Expr *CopyCtorArg =
5007  SourceLocation(), Param, false,
5008  Constructor->getLocation(), ParamType,
5009  VK_LValue, nullptr);
5010 
5011  SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
5012 
5013  // Cast to the base class to avoid ambiguities.
5014  QualType ArgTy =
5016  ParamType.getQualifiers());
5017 
5018  if (Moving) {
5019  CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
5020  }
5021 
5022  CXXCastPath BasePath;
5023  BasePath.push_back(BaseSpec);
5024  CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
5025  CK_UncheckedDerivedToBase,
5026  Moving ? VK_XValue : VK_LValue,
5027  &BasePath).get();
5028 
5029  InitializationKind InitKind
5030  = InitializationKind::CreateDirect(Constructor->getLocation(),
5032  InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
5033  BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
5034  break;
5035  }
5036  }
5037 
5038  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
5039  if (BaseInit.isInvalid())
5040  return true;
5041 
5042  CXXBaseInit =
5045  SourceLocation()),
5046  BaseSpec->isVirtual(),
5047  SourceLocation(),
5048  BaseInit.getAs<Expr>(),
5049  SourceLocation(),
5050  SourceLocation());
5051 
5052  return false;
5053 }
5054 
5055 static bool RefersToRValueRef(Expr *MemRef) {
5056  ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
5057  return Referenced->getType()->isRValueReferenceType();
5058 }
5059 
5060 static bool
5062  ImplicitInitializerKind ImplicitInitKind,
5063  FieldDecl *Field, IndirectFieldDecl *Indirect,
5064  CXXCtorInitializer *&CXXMemberInit) {
5065  if (Field->isInvalidDecl())
5066  return true;
5067 
5068  SourceLocation Loc = Constructor->getLocation();
5069 
5070  if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
5071  bool Moving = ImplicitInitKind == IIK_Move;
5072  ParmVarDecl *Param = Constructor->getParamDecl(0);
5073  QualType ParamType = Param->getType().getNonReferenceType();
5074 
5075  // Suppress copying zero-width bitfields.
5076  if (Field->isZeroLengthBitField(SemaRef.Context))
5077  return false;
5078 
5079  Expr *MemberExprBase =
5081  SourceLocation(), Param, false,
5082  Loc, ParamType, VK_LValue, nullptr);
5083 
5084  SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
5085 
5086  if (Moving) {
5087  MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
5088  }
5089 
5090  // Build a reference to this field within the parameter.
5091  CXXScopeSpec SS;
5092  LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
5094  MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
5095  : cast<ValueDecl>(Field), AS_public);
5096  MemberLookup.resolveKind();
5097  ExprResult CtorArg
5098  = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
5099  ParamType, Loc,
5100  /*IsArrow=*/false,
5101  SS,
5102  /*TemplateKWLoc=*/SourceLocation(),
5103  /*FirstQualifierInScope=*/nullptr,
5104  MemberLookup,
5105  /*TemplateArgs=*/nullptr,
5106  /*S*/nullptr);
5107  if (CtorArg.isInvalid())
5108  return true;
5109 
5110  // C++11 [class.copy]p15:
5111  // - if a member m has rvalue reference type T&&, it is direct-initialized
5112  // with static_cast<T&&>(x.m);
5113  if (RefersToRValueRef(CtorArg.get())) {
5114  CtorArg = CastForMoving(SemaRef, CtorArg.get());
5115  }
5116 
5117  InitializedEntity Entity =
5118  Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
5119  /*Implicit*/ true)
5120  : InitializedEntity::InitializeMember(Field, nullptr,
5121  /*Implicit*/ true);
5122 
5123  // Direct-initialize to use the copy constructor.
5124  InitializationKind InitKind =
5126 
5127  Expr *CtorArgE = CtorArg.getAs<Expr>();
5128  InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5129  ExprResult MemberInit =
5130  InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
5131  MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5132  if (MemberInit.isInvalid())
5133  return true;
5134 
5135  if (Indirect)
5136  CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5137  SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5138  else
5139  CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5140  SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5141  return false;
5142  }
5143 
5144  assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5145  "Unhandled implicit init kind!");
5146 
5147  QualType FieldBaseElementType =
5148  SemaRef.Context.getBaseElementType(Field->getType());
5149 
5150  if (FieldBaseElementType->isRecordType()) {
5151  InitializedEntity InitEntity =
5152  Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
5153  /*Implicit*/ true)
5154  : InitializedEntity::InitializeMember(Field, nullptr,
5155  /*Implicit*/ true);
5156  InitializationKind InitKind =
5158 
5159  InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
5160  ExprResult MemberInit =
5161  InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);
5162 
5163  MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5164  if (MemberInit.isInvalid())
5165  return true;
5166 
5167  if (Indirect)
5168  CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5169  Indirect, Loc,
5170  Loc,
5171  MemberInit.get(),
5172  Loc);
5173  else
5174  CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5175  Field, Loc, Loc,
5176  MemberInit.get(),
5177  Loc);
5178  return false;
5179  }
5180 
5181  if (!Field->getParent()->isUnion()) {
5182  if (FieldBaseElementType->isReferenceType()) {
5183  SemaRef.Diag(Constructor->getLocation(),
5184  diag::err_uninitialized_member_in_ctor)
5185  << (int)Constructor->isImplicit()
5186  << SemaRef.Context.getTagDeclType(Constructor->getParent())
5187  << 0 << Field->getDeclName();
5188  SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5189  return true;
5190  }
5191 
5192  if (FieldBaseElementType.isConstQualified()) {
5193  SemaRef.Diag(Constructor->getLocation(),
5194  diag::err_uninitialized_member_in_ctor)
5195  << (int)Constructor->isImplicit()
5196  << SemaRef.Context.getTagDeclType(Constructor->getParent())
5197  << 1 << Field->getDeclName();
5198  SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5199  return true;
5200  }
5201  }
5202 
5203  if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5204  // ARC and Weak:
5205  // Default-initialize Objective-C pointers to NULL.
5206  CXXMemberInit
5208  Loc, Loc,
5209  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5210  Loc);
5211  return false;
5212  }
5213 
5214  // Nothing to initialize.
5215  CXXMemberInit = nullptr;
5216  return false;
5217 }
5218 
5219 namespace {
5220 struct BaseAndFieldInfo {
5221  Sema &S;
5222  CXXConstructorDecl *Ctor;
5223  bool AnyErrorsInInits;
5225  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5227  llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5228 
5229  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5230  : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5231  bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5232  if (Ctor->getInheritedConstructor())
5233  IIK = IIK_Inherit;
5234  else if (Generated && Ctor->isCopyConstructor())
5235  IIK = IIK_Copy;
5236  else if (Generated && Ctor->isMoveConstructor())
5237  IIK = IIK_Move;
5238  else
5239  IIK = IIK_Default;
5240  }
5241 
5242  bool isImplicitCopyOrMove() const {
5243  switch (IIK) {
5244  case IIK_Copy:
5245  case IIK_Move:
5246  return true;
5247 
5248  case IIK_Default:
5249  case IIK_Inherit:
5250  return false;
5251  }
5252 
5253  llvm_unreachable("Invalid ImplicitInitializerKind!");
5254  }
5255 
5256  bool addFieldInitializer(CXXCtorInitializer *Init) {
5257  AllToInit.push_back(Init);
5258 
5259  // Check whether this initializer makes the field "used".
5260  if (Init->getInit()->HasSideEffects(S.Context))
5261  S.UnusedPrivateFields.remove(Init->getAnyMember());
5262 
5263  return false;
5264  }
5265 
5266  bool isInactiveUnionMember(FieldDecl *Field) {
5267  RecordDecl *Record = Field->getParent();
5268  if (!Record->isUnion())
5269  return false;
5270 
5271  if (FieldDecl *Active =
5272  ActiveUnionMember.lookup(Record->getCanonicalDecl()))
5273  return Active != Field->getCanonicalDecl();
5274 
5275  // In an implicit copy or move constructor, ignore any in-class initializer.
5276  if (isImplicitCopyOrMove())
5277  return true;
5278 
5279  // If there's no explicit initialization, the field is active only if it
5280  // has an in-class initializer...
5281  if (Field->hasInClassInitializer())
5282  return false;
5283  // ... or it's an anonymous struct or union whose class has an in-class
5284  // initializer.
5285  if (!Field->isAnonymousStructOrUnion())
5286  return true;
5287  CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5288  return !FieldRD->hasInClassInitializer();
5289  }
5290 
5291  /// Determine whether the given field is, or is within, a union member
5292  /// that is inactive (because there was an initializer given for a different
5293  /// member of the union, or because the union was not initialized at all).
5294  bool isWithinInactiveUnionMember(FieldDecl *Field,
5295  IndirectFieldDecl *Indirect) {
5296  if (!Indirect)
5297  return isInactiveUnionMember(Field);
5298 
5299  for (auto *C : Indirect->chain()) {
5300  FieldDecl *Field = dyn_cast<FieldDecl>(C);
5301  if (Field && isInactiveUnionMember(Field))
5302  return true;
5303  }
5304  return false;
5305  }
5306 };
5307 }
5308 
5309 /// Determine whether the given type is an incomplete or zero-lenfgth
5310 /// array type.
5312  if (T->isIncompleteArrayType())
5313  return true;
5314 
5315  while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5316  if (ArrayT->isZeroSize())
5317  return true;
5318 
5319  T = ArrayT->getElementType();
5320  }
5321 
5322  return false;
5323 }
5324 
5325 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5326  FieldDecl *Field,
5327  IndirectFieldDecl *Indirect = nullptr) {
5328  if (Field->isInvalidDecl())
5329  return false;
5330 
5331  // Overwhelmingly common case: we have a direct initializer for this field.
5332  if (CXXCtorInitializer *Init =
5333  Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5334  return Info.addFieldInitializer(Init);
5335 
5336  // C++11 [class.base.init]p8:
5337  // if the entity is a non-static data member that has a
5338  // brace-or-equal-initializer and either
5339  // -- the constructor's class is a union and no other variant member of that
5340  // union is designated by a mem-initializer-id or
5341  // -- the constructor's class is not a union, and, if the entity is a member
5342  // of an anonymous union, no other member of that union is designated by
5343  // a mem-initializer-id,
5344  // the entity is initialized as specified in [dcl.init].
5345  //
5346  // We also apply the same rules to handle anonymous structs within anonymous
5347  // unions.
5348  if (Info.isWithinInactiveUnionMember(Field, Indirect))
5349  return false;
5350 
5351  if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5352  ExprResult DIE =
5353  SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5354  if (DIE.isInvalid())
5355  return true;
5356 
5357  auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5358  SemaRef.checkInitializerLifetime(Entity, DIE.get());
5359 
5360  CXXCtorInitializer *Init;
5361  if (Indirect)
5362  Init = new (SemaRef.Context)
5364  SourceLocation(), DIE.get(), SourceLocation());
5365  else
5366  Init = new (SemaRef.Context)
5368  SourceLocation(), DIE.get(), SourceLocation());
5369  return Info.addFieldInitializer(Init);
5370  }
5371 
5372  // Don't initialize incomplete or zero-length arrays.
5373  if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5374  return false;
5375 
5376  // Don't try to build an implicit initializer if there were semantic
5377  // errors in any of the initializers (and therefore we might be
5378  // missing some that the user actually wrote).
5379  if (Info.AnyErrorsInInits)
5380  return false;
5381 
5382  CXXCtorInitializer *Init = nullptr;
5383  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5384  Indirect, Init))
5385  return true;
5386 
5387  if (!Init)
5388  return false;
5389 
5390  return Info.addFieldInitializer(Init);
5391 }
5392 
5393 bool
5395  CXXCtorInitializer *Initializer) {
5396  assert(Initializer->isDelegatingInitializer());
5397  Constructor->setNumCtorInitializers(1);
5398  CXXCtorInitializer **initializer =
5399  new (Context) CXXCtorInitializer*[1];
5400  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5401  Constructor->setCtorInitializers(initializer);
5402 
5403  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5404  MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5405  DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5406  }
5407 
5408  DelegatingCtorDecls.push_back(Constructor);
5409 
5410  DiagnoseUninitializedFields(*this, Constructor);
5411 
5412  return false;
5413 }
5414 
5415 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5416  ArrayRef<CXXCtorInitializer *> Initializers) {
5417  if (Constructor->isDependentContext()) {
5418  // Just store the initializers as written, they will be checked during
5419  // instantiation.
5420  if (!Initializers.empty()) {
5421  Constructor->setNumCtorInitializers(Initializers.size());
5422  CXXCtorInitializer **baseOrMemberInitializers =
5423  new (Context) CXXCtorInitializer*[Initializers.size()];
5424  memcpy(baseOrMemberInitializers, Initializers.data(),
5425  Initializers.size() * sizeof(CXXCtorInitializer*));
5426  Constructor->setCtorInitializers(baseOrMemberInitializers);
5427  }
5428 
5429  // Let template instantiation know whether we had errors.
5430  if (AnyErrors)
5431  Constructor->setInvalidDecl();
5432 
5433  return false;
5434  }
5435 
5436  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5437 
5438  // We need to build the initializer AST according to order of construction
5439  // and not what user specified in the Initializers list.
5440  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5441  if (!ClassDecl)
5442  return true;
5443 
5444  bool HadError = false;
5445 
5446  for (unsigned i = 0; i < Initializers.size(); i++) {
5447  CXXCtorInitializer *Member = Initializers[i];
5448 
5449  if (Member->isBaseInitializer())
5450  Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5451  else {
5452  Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5453 
5454  if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5455  for (auto *C : F->chain()) {
5456  FieldDecl *FD = dyn_cast<FieldDecl>(C);
5457  if (FD && FD->getParent()->isUnion())
5458  Info.ActiveUnionMember.insert(std::make_pair(
5459  FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5460  }
5461  } else if (FieldDecl *FD = Member->getMember()) {
5462  if (FD->getParent()->isUnion())
5463  Info.ActiveUnionMember.insert(std::make_pair(
5464  FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5465  }
5466  }
5467  }
5468 
5469  // Keep track of the direct virtual bases.
5471  for (auto &I : ClassDecl->bases()) {
5472  if (I.isVirtual())
5473  DirectVBases.insert(&I);
5474  }
5475 
5476  // Push virtual bases before others.
5477  for (auto &VBase : ClassDecl->vbases()) {
5479  = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5480  // [class.base.init]p7, per DR257:
5481  // A mem-initializer where the mem-initializer-id names a virtual base
5482  // class is ignored during execution of a constructor of any class that
5483  // is not the most derived class.
5484  if (ClassDecl->isAbstract()) {
5485  // FIXME: Provide a fixit to remove the base specifier. This requires
5486  // tracking the location of the associated comma for a base specifier.
5487  Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5488  << VBase.getType() << ClassDecl;
5489  DiagnoseAbstractType(ClassDecl);
5490  }
5491 
5492  Info.AllToInit.push_back(Value);
5493  } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5494  // [class.base.init]p8, per DR257:
5495  // If a given [...] base class is not named by a mem-initializer-id
5496  // [...] and the entity is not a virtual base class of an abstract
5497  // class, then [...] the entity is default-initialized.
5498  bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5499  CXXCtorInitializer *CXXBaseInit;
5500  if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5501  &VBase, IsInheritedVirtualBase,
5502  CXXBaseInit)) {
5503  HadError = true;
5504  continue;
5505  }
5506 
5507  Info.AllToInit.push_back(CXXBaseInit);
5508  }
5509  }
5510 
5511  // Non-virtual bases.
5512  for (auto &Base : ClassDecl->bases()) {
5513  // Virtuals are in the virtual base list and already constructed.
5514  if (Base.isVirtual())
5515  continue;
5516 
5518  = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5519  Info.AllToInit.push_back(Value);
5520  } else if (!AnyErrors) {
5521  CXXCtorInitializer *CXXBaseInit;
5522  if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5523  &Base, /*IsInheritedVirtualBase=*/false,
5524  CXXBaseInit)) {
5525  HadError = true;
5526  continue;
5527  }
5528 
5529  Info.AllToInit.push_back(CXXBaseInit);
5530  }
5531  }
5532 
5533  // Fields.
5534  for (auto *Mem : ClassDecl->decls()) {
5535  if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5536  // C++ [class.bit]p2:
5537  // A declaration for a bit-field that omits the identifier declares an
5538  // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5539  // initialized.
5540  if (F->isUnnamedBitField())
5541  continue;
5542 
5543  // If we're not generating the implicit copy/move constructor, then we'll
5544  // handle anonymous struct/union fields based on their individual
5545  // indirect fields.
5546  if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5547  continue;
5548 
5549  if (CollectFieldInitializer(*this, Info, F))
5550  HadError = true;
5551  continue;
5552  }
5553 
5554  // Beyond this point, we only consider default initialization.
5555  if (Info.isImplicitCopyOrMove())
5556  continue;
5557 
5558  if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5559  if (F->getType()->isIncompleteArrayType()) {
5560  assert(ClassDecl->hasFlexibleArrayMember() &&
5561  "Incomplete array type is not valid");
5562  continue;
5563  }
5564 
5565  // Initialize each field of an anonymous struct individually.
5566  if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5567  HadError = true;
5568 
5569  continue;
5570  }
5571  }
5572 
5573  unsigned NumInitializers = Info.AllToInit.size();
5574  if (NumInitializers > 0) {
5575  Constructor->setNumCtorInitializers(NumInitializers);
5576  CXXCtorInitializer **baseOrMemberInitializers =
5577  new (Context) CXXCtorInitializer*[NumInitializers];
5578  memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5579  NumInitializers * sizeof(CXXCtorInitializer*));
5580  Constructor->setCtorInitializers(baseOrMemberInitializers);
5581 
5582  // Constructors implicitly reference the base and member
5583  // destructors.
5584  MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5585  Constructor->getParent());
5586  }
5587 
5588  return HadError;
5589 }
5590 
5592  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5593  const RecordDecl *RD = RT->getDecl();
5594  if (RD->isAnonymousStructOrUnion()) {
5595  for (auto *Field : RD->fields())
5596  PopulateKeysForFields(Field, IdealInits);
5597  return;
5598  }
5599  }
5600  IdealInits.push_back(Field->getCanonicalDecl());
5601 }
5602 
5603 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5604  return Context.getCanonicalType(BaseType).getTypePtr();
5605 }
5606 
5607 static const void *GetKeyForMember(ASTContext &Context,
5608  CXXCtorInitializer *Member) {
5609  if (!Member->isAnyMemberInitializer())
5610  return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5611 
5612  return Member->getAnyMember()->getCanonicalDecl();
5613 }
5614 
5615 static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5617  const CXXCtorInitializer *Current) {
5618  if (Previous->isAnyMemberInitializer())
5619  Diag << 0 << Previous->getAnyMember();
5620  else
5621  Diag << 1 << Previous->getTypeSourceInfo()->getType();
5622 
5623  if (Current->isAnyMemberInitializer())
5624  Diag << 0 << Current->getAnyMember();
5625  else
5626  Diag << 1 << Current->getTypeSourceInfo()->getType();
5627 }
5628 
5630  Sema &SemaRef, const CXXConstructorDecl *Constructor,
5632  if (Constructor->getDeclContext()->isDependentContext())
5633  return;
5634 
5635  // Don't check initializers order unless the warning is enabled at the
5636  // location of at least one initializer.
5637  bool ShouldCheckOrder = false;
5638  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5639  CXXCtorInitializer *Init = Inits[InitIndex];
5640  if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5641  Init->getSourceLocation())) {
5642  ShouldCheckOrder = true;
5643  break;
5644  }
5645  }
5646  if (!ShouldCheckOrder)
5647  return;
5648 
5649  // Build the list of bases and members in the order that they'll
5650  // actually be initialized. The explicit initializers should be in
5651  // this same order but may be missing things.
5652  SmallVector<const void*, 32> IdealInitKeys;
5653 
5654  const CXXRecordDecl *ClassDecl = Constructor->getParent();
5655 
5656  // 1. Virtual bases.
5657  for (const auto &VBase : ClassDecl->vbases())
5658  IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5659 
5660  // 2. Non-virtual bases.
5661  for (const auto &Base : ClassDecl->bases()) {
5662  if (Base.isVirtual())
5663  continue;
5664  IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5665  }
5666 
5667  // 3. Direct fields.
5668  for (auto *Field : ClassDecl->fields()) {
5669  if (Field->isUnnamedBitField())
5670  continue;
5671 
5672  PopulateKeysForFields(Field, IdealInitKeys);
5673  }
5674 
5675  unsigned NumIdealInits = IdealInitKeys.size();
5676  unsigned IdealIndex = 0;
5677 
5678  // Track initializers that are in an incorrect order for either a warning or
5679  // note if multiple ones occur.
5680  SmallVector<unsigned> WarnIndexes;
5681  // Correlates the index of an initializer in the init-list to the index of
5682  // the field/base in the class.
5683  SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5684 
5685  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5686  const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5687 
5688  // Scan forward to try to find this initializer in the idealized
5689  // initializers list.
5690  for (; IdealIndex != NumIdealInits; ++IdealIndex)
5691  if (InitKey == IdealInitKeys[IdealIndex])
5692  break;
5693 
5694  // If we didn't find this initializer, it must be because we
5695  // scanned past it on a previous iteration. That can only
5696  // happen if we're out of order; emit a warning.
5697  if (IdealIndex == NumIdealInits && InitIndex) {
5698  WarnIndexes.push_back(InitIndex);
5699 
5700  // Move back to the initializer's location in the ideal list.
5701  for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5702  if (InitKey == IdealInitKeys[IdealIndex])
5703  break;
5704 
5705  assert(IdealIndex < NumIdealInits &&
5706  "initializer not found in initializer list");
5707  }
5708  CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5709  }
5710 
5711  if (WarnIndexes.empty())
5712  return;
5713 
5714  // Sort based on the ideal order, first in the pair.
5715  llvm::sort(CorrelatedInitOrder, llvm::less_first());
5716 
5717  // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5718  // emit the diagnostic before we can try adding notes.
5719  {
5720  Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5721  Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5722  WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5723  : diag::warn_some_initializers_out_of_order);
5724 
5725  for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5726  if (CorrelatedInitOrder[I].second == I)
5727  continue;
5728  // Ideally we would be using InsertFromRange here, but clang doesn't
5729  // appear to handle InsertFromRange correctly when the source range is
5730  // modified by another fix-it.
5732  Inits[I]->getSourceRange(),
5735  Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5737  }
5738 
5739  // If there is only 1 item out of order, the warning expects the name and
5740  // type of each being added to it.
5741  if (WarnIndexes.size() == 1) {
5742  AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5743  Inits[WarnIndexes.front()]);
5744  return;
5745  }
5746  }
5747  // More than 1 item to warn, create notes letting the user know which ones
5748  // are bad.
5749  for (unsigned WarnIndex : WarnIndexes) {
5750  const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5751  auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5752  diag::note_initializer_out_of_order);
5753  AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5754  D << PrevInit->getSourceRange();
5755  }
5756 }
5757 
5758 namespace {
5759 bool CheckRedundantInit(Sema &S,
5760  CXXCtorInitializer *Init,
5761  CXXCtorInitializer *&PrevInit) {
5762  if (!PrevInit) {
5763  PrevInit = Init;
5764  return false;
5765  }
5766 
5767  if (FieldDecl *Field = Init->getAnyMember())
5768  S.Diag(Init->getSourceLocation(),
5769  diag::err_multiple_mem_initialization)
5770  << Field->getDeclName()
5771  << Init->getSourceRange();
5772  else {
5773  const Type *BaseClass = Init->getBaseClass();
5774  assert(BaseClass && "neither field nor base");
5775  S.Diag(Init->getSourceLocation(),
5776  diag::err_multiple_base_initialization)
5777  << QualType(BaseClass, 0)
5778  << Init->getSourceRange();
5779  }
5780  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5781  << 0 << PrevInit->getSourceRange();
5782 
5783  return true;
5784 }
5785 
5786 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5787 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5788 
5789 bool CheckRedundantUnionInit(Sema &S,
5790  CXXCtorInitializer *Init,
5791  RedundantUnionMap &Unions) {
5792  FieldDecl *Field = Init->getAnyMember();
5793  RecordDecl *Parent = Field->getParent();
5794  NamedDecl *Child = Field;
5795 
5796  while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5797  if (Parent->isUnion()) {
5798  UnionEntry &En = Unions[Parent];
5799  if (En.first && En.first != Child) {
5800  S.Diag(Init->getSourceLocation(),
5801  diag::err_multiple_mem_union_initialization)
5802  << Field->getDeclName()
5803  << Init->getSourceRange();
5804  S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5805  << 0 << En.second->getSourceRange();
5806  return true;
5807  }
5808  if (!En.first) {
5809  En.first = Child;
5810  En.second = Init;
5811  }
5812  if (!Parent->isAnonymousStructOrUnion())
5813  return false;
5814  }
5815 
5816  Child = Parent;
5817  Parent = cast<RecordDecl>(Parent->getDeclContext());
5818  }
5819 
5820  return false;
5821 }
5822 } // namespace
5823 
5824 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5825 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5826  SourceLocation ColonLoc,
5828  bool AnyErrors) {
5829  if (!ConstructorDecl)
5830  return;
5831 
5832  AdjustDeclIfTemplate(ConstructorDecl);
5833 
5834  CXXConstructorDecl *Constructor
5835  = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5836 
5837  if (!Constructor) {
5838  Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5839  return;
5840  }
5841 
5842  // Mapping for the duplicate initializers check.
5843  // For member initializers, this is keyed with a FieldDecl*.
5844  // For base initializers, this is keyed with a Type*.
5845  llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5846 
5847  // Mapping for the inconsistent anonymous-union initializers check.
5848  RedundantUnionMap MemberUnions;
5849 
5850  bool HadError = false;
5851  for (unsigned i = 0; i < MemInits.size(); i++) {
5852  CXXCtorInitializer *Init = MemInits[i];
5853 
5854  // Set the source order index.
5855  Init->setSourceOrder(i);
5856 
5857  if (Init->isAnyMemberInitializer()) {
5858  const void *Key = GetKeyForMember(Context, Init);
5859  if (CheckRedundantInit(*this, Init, Members[Key]) ||
5860  CheckRedundantUnionInit(*this, Init, MemberUnions))
5861  HadError = true;
5862  } else if (Init->isBaseInitializer()) {
5863  const void *Key = GetKeyForMember(Context, Init);
5864  if (CheckRedundantInit(*this, Init, Members[Key]))
5865  HadError = true;
5866  } else {
5867  assert(Init->isDelegatingInitializer());
5868  // This must be the only initializer
5869  if (MemInits.size() != 1) {
5870  Diag(Init->getSourceLocation(),
5871  diag::err_delegating_initializer_alone)
5872  << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5873  // We will treat this as being the only initializer.
5874  }
5875  SetDelegatingInitializer(Constructor, MemInits[i]);
5876  // Return immediately as the initializer is set.
5877  return;
5878  }
5879  }
5880 
5881  if (HadError)
5882  return;
5883 
5884  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5885 
5886  SetCtorInitializers(Constructor, AnyErrors, MemInits);
5887 
5888  DiagnoseUninitializedFields(*this, Constructor);
5889 }
5890 
5891 void
5893  CXXRecordDecl *ClassDecl) {
5894  // Ignore dependent contexts. Also ignore unions, since their members never
5895  // have destructors implicitly called.
5896  if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5897  return;
5898 
5899  // FIXME: all the access-control diagnostics are positioned on the
5900  // field/base declaration. That's probably good; that said, the
5901  // user might reasonably want to know why the destructor is being
5902  // emitted, and we currently don't say.
5903 
5904  // Non-static data members.
5905  for (auto *Field : ClassDecl->fields()) {
5906  if (Field->isInvalidDecl())
5907  continue;
5908 
5909  // Don't destroy incomplete or zero-length arrays.
5910  if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5911  continue;
5912 
5913  QualType FieldType = Context.getBaseElementType(Field->getType());
5914 
5915  const RecordType* RT = FieldType->getAs<RecordType>();
5916  if (!RT)
5917  continue;
5918 
5919  CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5920  if (FieldClassDecl->isInvalidDecl())
5921  continue;
5922  if (FieldClassDecl->hasIrrelevantDestructor())
5923  continue;
5924  // The destructor for an implicit anonymous union member is never invoked.
5925  if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5926  continue;
5927 
5928  CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5929  // Dtor might still be missing, e.g because it's invalid.
5930  if (!Dtor)
5931  continue;
5932  CheckDestructorAccess(Field->getLocation(), Dtor,
5933  PDiag(diag::err_access_dtor_field)
5934  << Field->getDeclName()
5935  << FieldType);
5936 
5937  MarkFunctionReferenced(Location, Dtor);
5938  DiagnoseUseOfDecl(Dtor, Location);
5939  }
5940 
5941  // We only potentially invoke the destructors of potentially constructed
5942  // subobjects.
5943  bool VisitVirtualBases = !ClassDecl->isAbstract();
5944 
5945  // If the destructor exists and has already been marked used in the MS ABI,
5946  // then virtual base destructors have already been checked and marked used.
5947  // Skip checking them again to avoid duplicate diagnostics.
5949  CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5950  if (Dtor && Dtor->isUsed())
5951  VisitVirtualBases = false;
5952  }
5953 
5954  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5955 
5956  // Bases.
5957  for (const auto &Base : ClassDecl->bases()) {
5958  const RecordType *RT = Base.getType()->getAs<RecordType>();
5959  if (!RT)
5960  continue;
5961 
5962  // Remember direct virtual bases.
5963  if (Base.isVirtual()) {
5964  if (!VisitVirtualBases)
5965  continue;
5966  DirectVirtualBases.insert(RT);
5967  }
5968 
5969  CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5970  // If our base class is invalid, we probably can't get its dtor anyway.
5971  if (BaseClassDecl->isInvalidDecl())
5972  continue;
5973  if (BaseClassDecl->hasIrrelevantDestructor())
5974  continue;
5975 
5976  CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5977  // Dtor might still be missing, e.g because it's invalid.
5978  if (!Dtor)
5979  continue;
5980 
5981  // FIXME: caret should be on the start of the class name
5982  CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5983  PDiag(diag::err_access_dtor_base)
5984  << Base.getType() << Base.getSourceRange(),
5985  Context.getTypeDeclType(ClassDecl));
5986 
5987  MarkFunctionReferenced(Location, Dtor);
5988  DiagnoseUseOfDecl(Dtor, Location);
5989  }
5990 
5991  if (VisitVirtualBases)
5992  MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5993  &DirectVirtualBases);
5994 }
5995 
5997  SourceLocation Location, CXXRecordDecl *ClassDecl,
5998  llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5999  // Virtual bases.
6000  for (const auto &VBase : ClassDecl->vbases()) {
6001  // Bases are always records in a well-formed non-dependent class.
6002  const RecordType *RT = VBase.getType()->castAs<RecordType>();
6003 
6004  // Ignore already visited direct virtual bases.
6005  if (DirectVirtualBases && DirectVirtualBases->count(RT))
6006  continue;
6007 
6008  CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
6009  // If our base class is invalid, we probably can't get its dtor anyway.
6010  if (BaseClassDecl->isInvalidDecl())
6011  continue;
6012  if (BaseClassDecl->hasIrrelevantDestructor())
6013  continue;
6014 
6015  CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
6016  // Dtor might still be missing, e.g because it's invalid.
6017  if (!Dtor)
6018  continue;
6020  ClassDecl->getLocation(), Dtor,
6021  PDiag(diag::err_access_dtor_vbase)
6022  << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
6023  Context.getTypeDeclType(ClassDecl)) ==
6024  AR_accessible) {
6026  Context.getTypeDeclType(ClassDecl), VBase.getType(),
6027  diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
6028  SourceRange(), DeclarationName(), nullptr);
6029  }
6030 
6031  MarkFunctionReferenced(Location, Dtor);
6032  DiagnoseUseOfDecl(Dtor, Location);
6033  }
6034 }
6035 
6037  if (!CDtorDecl)
6038  return;
6039 
6040  if (CXXConstructorDecl *Constructor
6041  = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
6042  if (CXXRecordDecl *ClassDecl = Constructor->getParent();
6043  !ClassDecl || ClassDecl->isInvalidDecl()) {
6044  return;
6045  }
6046  SetCtorInitializers(Constructor, /*AnyErrors=*/false);
6047  DiagnoseUninitializedFields(*this, Constructor);
6048  }
6049 }
6050 
6052  if (!getLangOpts().CPlusPlus)
6053  return false;
6054 
6055  const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
6056  if (!RD)
6057  return false;
6058 
6059  // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
6060  // class template specialization here, but doing so breaks a lot of code.
6061 
6062  // We can't answer whether something is abstract until it has a
6063  // definition. If it's currently being defined, we'll walk back
6064  // over all the declarations when we have a full definition.
6065  const CXXRecordDecl *Def = RD->getDefinition();
6066  if (!Def || Def->isBeingDefined())
6067  return false;
6068 
6069  return RD->isAbstract();
6070 }
6071 
6073  TypeDiagnoser &Diagnoser) {
6074  if (!isAbstractType(Loc, T))
6075  return false;
6076 
6078  Diagnoser.diagnose(*this, Loc, T);
6080  return true;
6081 }
6082 
6084  // Check if we've already emitted the list of pure virtual functions
6085  // for this class.
6087  return;
6088 
6089  // If the diagnostic is suppressed, don't emit the notes. We're only
6090  // going to emit them once, so try to attach them to a diagnostic we're
6091  // actually going to show.
6093  return;
6094 
6095  CXXFinalOverriderMap FinalOverriders;
6096  RD->getFinalOverriders(FinalOverriders);
6097 
6098  // Keep a set of seen pure methods so we won't diagnose the same method
6099  // more than once.
6101 
6102  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
6103  MEnd = FinalOverriders.end();
6104  M != MEnd;
6105  ++M) {
6106  for (OverridingMethods::iterator SO = M->second.begin(),
6107  SOEnd = M->second.end();
6108  SO != SOEnd; ++SO) {
6109  // C++ [class.abstract]p4:
6110  // A class is abstract if it contains or inherits at least one
6111  // pure virtual function for which the final overrider is pure
6112  // virtual.
6113 
6114  //
6115  if (SO->second.size() != 1)
6116  continue;
6117 
6118  if (!SO->second.front().Method->isPureVirtual())
6119  continue;
6120 
6121  if (!SeenPureMethods.insert(SO->second.front().Method).second)
6122  continue;
6123 
6124  Diag(SO->second.front().Method->getLocation(),
6125  diag::note_pure_virtual_function)
6126  << SO->second.front().Method->getDeclName() << RD->getDeclName();
6127  }
6128  }
6129 
6132  PureVirtualClassDiagSet->insert(RD);
6133 }
6134 
6135 namespace {
6136 struct AbstractUsageInfo {
6137  Sema &S;
6139  CanQualType AbstractType;
6140  bool Invalid;
6141 
6142  AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6143  : S(S), Record(Record),
6144  AbstractType(S.Context.getCanonicalType(
6145  S.Context.getTypeDeclType(Record))),
6146  Invalid(false) {}
6147 
6148  void DiagnoseAbstractType() {
6149  if (Invalid) return;
6151  Invalid = true;
6152  }
6153 
6154  void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6155 };
6156 
6157 struct CheckAbstractUsage {
6158  AbstractUsageInfo &Info;
6159  const NamedDecl *Ctx;
6160 
6161  CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6162  : Info(Info), Ctx(Ctx) {}
6163 
6164  void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6165  switch (TL.getTypeLocClass()) {
6166 #define ABSTRACT_TYPELOC(CLASS, PARENT)
6167 #define TYPELOC(CLASS, PARENT) \
6168  case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6169 #include "clang/AST/TypeLocNodes.def"
6170  }
6171  }
6172 
6173  void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6175  for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6176  if (!TL.getParam(I))
6177  continue;
6178 
6179  TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
6180  if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
6181  }
6182  }
6183 
6184  void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6186  }
6187 
6189  // Visit the type parameters from a permissive context.
6190  for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6191  TemplateArgumentLoc TAL = TL.getArgLoc(I);
6193  if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6194  Visit(TSI->getTypeLoc(), Sema::AbstractNone);
6195  // TODO: other template argument types?
6196  }
6197  }
6198 
6199  // Visit pointee types from a permissive context.
6200 #define CheckPolymorphic(Type) \
6201  void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6202  Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6203  }
6209 
6210  /// Handle all the types we haven't given a more specific
6211  /// implementation for above.
6212  void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6213  // Every other kind of type that we haven't called out already
6214  // that has an inner type is either (1) sugar or (2) contains that
6215  // inner type in some way as a subobject.
6216  if (TypeLoc Next = TL.getNextTypeLoc())
6217  return Visit(Next, Sel);
6218 
6219  // If there's no inner type and we're in a permissive context,
6220  // don't diagnose.
6221  if (Sel == Sema::AbstractNone) return;
6222 
6223  // Check whether the type matches the abstract type.
6224  QualType T = TL.getType();
6225  if (T->isArrayType()) {
6227  T = Info.S.Context.getBaseElementType(T);
6228  }
6230  if (CT != Info.AbstractType) return;
6231 
6232  // It matched; do some magic.
6233  // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6234  if (Sel == Sema::AbstractArrayType) {
6235  Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
6236  << T << TL.getSourceRange();
6237  } else {
6238  Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
6239  << Sel << T << TL.getSourceRange();
6240  }
6241  Info.DiagnoseAbstractType();
6242  }
6243 };
6244 
6245 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6247  CheckAbstractUsage(*this, D).Visit(TL, Sel);
6248 }
6249 
6250 }
6251 
6252 /// Check for invalid uses of an abstract type in a function declaration.
6253 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6254  FunctionDecl *FD) {
6255  // Only definitions are required to refer to complete and
6256  // non-abstract types.
6257  if (!FD->doesThisDeclarationHaveABody())
6258  return;
6259 
6260  // For safety's sake, just ignore it if we don't have type source
6261  // information. This should never happen for non-implicit methods,
6262  // but...
6263  if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6264  Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
6265 }
6266 
6267 /// Check for invalid uses of an abstract type in a variable0 declaration.
6268 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6269  VarDecl *VD) {
6270  // No need to do the check on definitions, which require that
6271  // the type is complete.
6272  if (VD->isThisDeclarationADefinition())
6273  return;
6274 
6275  Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
6277 }
6278 
6279 /// Check for invalid uses of an abstract type within a class definition.
6280 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6281  CXXRecordDecl *RD) {
6282  for (auto *D : RD->decls()) {
6283  if (D->isImplicit()) continue;
6284 
6285  // Step through friends to the befriended declaration.
6286  if (auto *FD = dyn_cast<FriendDecl>(D)) {
6287  D = FD->getFriendDecl();
6288  if (!D) continue;
6289  }
6290 
6291  // Functions and function templates.
6292  if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6293  CheckAbstractClassUsage(Info, FD);
6294  } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6295  CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6296 
6297  // Fields and static variables.
6298  } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6299  if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6300  Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6301  } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6302  CheckAbstractClassUsage(Info, VD);
6303  } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6304  CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6305 
6306  // Nested classes and class templates.
6307  } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6308  CheckAbstractClassUsage(Info, RD);
6309  } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6310  CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6311  }
6312  }
6313 }
6314 
6316  Attr *ClassAttr = getDLLAttr(Class);
6317  if (!ClassAttr)
6318  return;
6319 
6320  assert(ClassAttr->getKind() == attr::DLLExport);
6321 
6322  TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6323 
6325  // Don't go any further if this is just an explicit instantiation
6326  // declaration.
6327  return;
6328 
6329  // Add a context note to explain how we got to any diagnostics produced below.
6330  struct MarkingClassDllexported {
6331  Sema &S;
6332  MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6333  SourceLocation AttrLoc)
6334  : S(S) {
6337  Ctx.PointOfInstantiation = AttrLoc;
6338  Ctx.Entity = Class;
6339  S.pushCodeSynthesisContext(Ctx);
6340  }
6341  ~MarkingClassDllexported() {
6343  }
6344  } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6345 
6346  if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
6347  S.MarkVTableUsed(Class->getLocation(), Class, true);
6348 
6349  for (Decl *Member : Class->decls()) {
6350  // Skip members that were not marked exported.
6351  if (!Member->hasAttr<DLLExportAttr>())
6352  continue;
6353 
6354  // Defined static variables that are members of an exported base
6355  // class must be marked export too.
6356  auto *VD = dyn_cast<VarDecl>(Member);
6357  if (VD && VD->getStorageClass() == SC_Static &&
6359  S.MarkVariableReferenced(VD->getLocation(), VD);
6360 
6361  auto *MD = dyn_cast<CXXMethodDecl>(Member);
6362  if (!MD)
6363  continue;
6364 
6365  if (MD->isUserProvided()) {
6366  // Instantiate non-default class member functions ...
6367 
6368  // .. except for certain kinds of template specializations.
6369  if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6370  continue;
6371 
6372  // If this is an MS ABI dllexport default constructor, instantiate any
6373  // default arguments.
6375  auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6376  if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6378  }
6379  }
6380 
6381  S.MarkFunctionReferenced(Class->getLocation(), MD);
6382 
6383  // The function will be passed to the consumer when its definition is
6384  // encountered.
6385  } else if (MD->isExplicitlyDefaulted()) {
6386  // Synthesize and instantiate explicitly defaulted methods.
6387  S.MarkFunctionReferenced(Class->getLocation(), MD);
6388 
6390  // Except for explicit instantiation defs, we will not see the
6391  // definition again later, so pass it to the consumer now.
6393  }
6394  } else if (!MD->isTrivial() ||
6395  MD->isCopyAssignmentOperator() ||
6396  MD->isMoveAssignmentOperator()) {
6397  // Synthesize and instantiate non-trivial implicit methods, and the copy
6398  // and move assignment operators. The latter are exported even if they
6399  // are trivial, because the address of an operator can be taken and
6400  // should compare equal across libraries.
6401  S.MarkFunctionReferenced(Class->getLocation(), MD);
6402 
6403  // There is no later point when we will see the definition of this
6404  // function, so pass it to the consumer now.
6406  }
6407  }
6408 }
6409 
6411  CXXRecordDecl *Class) {
6412  // Only the MS ABI has default constructor closures, so we don't need to do
6413  // this semantic checking anywhere else.
6415  return;
6416 
6417  CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6418  for (Decl *Member : Class->decls()) {
6419  // Look for exported default constructors.
6420  auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6421  if (!CD || !CD->isDefaultConstructor())
6422  continue;
6423  auto *Attr = CD->getAttr<DLLExportAttr>();
6424  if (!Attr)
6425  continue;
6426 
6427  // If the class is non-dependent, mark the default arguments as ODR-used so
6428  // that we can properly codegen the constructor closure.
6429  if (!Class->isDependentContext()) {
6430  for (ParmVarDecl *PD : CD->parameters()) {
6431  (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6433  }
6434  }
6435 
6436  if (LastExportedDefaultCtor) {
6437  S.Diag(LastExportedDefaultCtor->getLocation(),
6438  diag::err_attribute_dll_ambiguous_default_ctor)
6439  << Class;
6440  S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6441  << CD->getDeclName();
6442  return;
6443  }
6444  LastExportedDefaultCtor = CD;
6445  }
6446 }
6447 
6449  CXXRecordDecl *Class) {
6450  bool ErrorReported = false;
6451  auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6452  ClassTemplateDecl *TD) {
6453  if (ErrorReported)
6454  return;
6455  S.Diag(TD->getLocation(),
6456  diag::err_cuda_device_builtin_surftex_cls_template)
6457  << /*surface*/ 0 << TD;
6458  ErrorReported = true;
6459  };
6460 
6461  ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6462  if (!TD) {
6463  auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6464  if (!SD) {
6465  S.Diag(Class->getLocation(),
6466  diag::err_cuda_device_builtin_surftex_ref_decl)
6467  << /*surface*/ 0 << Class;
6468  S.Diag(Class->getLocation(),
6469  diag::note_cuda_device_builtin_surftex_should_be_template_class)
6470  << Class;
6471  return;
6472  }
6473  TD = SD->getSpecializedTemplate();
6474  }
6475 
6477  unsigned N = Params->size();
6478 
6479  if (N != 2) {
6480  reportIllegalClassTemplate(S, TD);
6481  S.Diag(TD->getLocation(),
6482  diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6483  << TD << 2;
6484  }
6485  if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6486  reportIllegalClassTemplate(S, TD);
6487  S.Diag(TD->getLocation(),
6488  diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6489  << TD << /*1st*/ 0 << /*type*/ 0;
6490  }
6491  if (N > 1) {
6492  auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6493  if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6494  reportIllegalClassTemplate(S, TD);
6495  S.Diag(TD->getLocation(),
6496  diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6497  << TD << /*2nd*/ 1 << /*integer*/ 1;
6498  }
6499  }
6500 }
6501 
6503  CXXRecordDecl *Class) {
6504  bool ErrorReported = false;
6505  auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6506  ClassTemplateDecl *TD) {
6507  if (ErrorReported)
6508  return;
6509  S.Diag(TD->getLocation(),
6510  diag::err_cuda_device_builtin_surftex_cls_template)
6511  << /*texture*/ 1 << TD;
6512  ErrorReported = true;
6513  };
6514 
6515  ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6516  if (!TD) {
6517  auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6518  if (!SD) {
6519  S.Diag(Class->getLocation(),
6520  diag::err_cuda_device_builtin_surftex_ref_decl)
6521  << /*texture*/ 1 << Class;
6522  S.Diag(Class->getLocation(),
6523  diag::note_cuda_device_builtin_surftex_should_be_template_class)
6524  << Class;
6525  return;
6526  }
6527  TD = SD->getSpecializedTemplate();
6528  }
6529 
6531  unsigned N = Params->size();
6532 
6533  if (N != 3) {
6534  reportIllegalClassTemplate(S, TD);
6535  S.Diag(TD->getLocation(),
6536  diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6537  << TD << 3;
6538  }
6539  if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6540  reportIllegalClassTemplate(S, TD);
6541  S.Diag(TD->getLocation(),
6542  diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6543  << TD << /*1st*/ 0 << /*type*/ 0;
6544  }
6545  if (N > 1) {
6546  auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6547  if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6548  reportIllegalClassTemplate(S, TD);
6549  S.Diag(TD->getLocation(),
6550  diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6551  << TD << /*2nd*/ 1 << /*integer*/ 1;
6552  }
6553  }
6554  if (N > 2) {
6555  auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6556  if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6557  reportIllegalClassTemplate(S, TD);
6558  S.Diag(TD->getLocation(),
6559  diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6560  << TD << /*3rd*/ 2 << /*integer*/ 1;
6561  }
6562  }
6563 }
6564 
6566  // Mark any compiler-generated routines with the implicit code_seg attribute.
6567  for (auto *Method : Class->methods()) {
6568  if (Method->isUserProvided())
6569  continue;
6570  if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6571  Method->addAttr(A);
6572  }
6573 }
6574 
6575 /// Check class-level dllimport/dllexport attribute.
6577  Attr *ClassAttr = getDLLAttr(Class);
6578 
6579  // MSVC inherits DLL attributes to partial class template specializations.
6580  if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6581  if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6582  if (Attr *TemplateAttr =
6583  getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6584  auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6585  A->setInherited(true);
6586  ClassAttr = A;
6587  }
6588  }
6589  }
6590 
6591  if (!ClassAttr)
6592  return;
6593 
6594  // MSVC allows imported or exported template classes that have UniqueExternal
6595  // linkage. This occurs when the template class has been instantiated with
6596  // a template parameter which itself has internal linkage.
6597  // We drop the attribute to avoid exporting or importing any members.
6599  Context.getTargetInfo().getTriple().isPS()) &&
6600  (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6601  Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6602  return;
6603  }
6604 
6605  if (!Class->isExternallyVisible()) {
6606  Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6607  << Class << ClassAttr;
6608  return;
6609  }
6610 
6612  !ClassAttr->isInherited()) {
6613  // Diagnose dll attributes on members of class with dll attribute.
6614  for (Decl *Member : Class->decls()) {
6615  if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6616  continue;
6617  InheritableAttr *MemberAttr = getDLLAttr(Member);
6618  if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6619  continue;
6620 
6621  Diag(MemberAttr->getLocation(),
6622  diag::err_attribute_dll_member_of_dll_class)
6623  << MemberAttr << ClassAttr;
6624  Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6625  Member->setInvalidDecl();
6626  }
6627  }
6628 
6629  if (Class->getDescribedClassTemplate())
6630  // Don't inherit dll attribute until the template is instantiated.
6631  return;
6632 
6633  // The class is either imported or exported.
6634  const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6635 
6636  // Check if this was a dllimport attribute propagated from a derived class to
6637  // a base class template specialization. We don't apply these attributes to
6638  // static data members.
6639  const bool PropagatedImport =
6640  !ClassExported &&
6641  cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6642 
6643  TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6644 
6645  // Ignore explicit dllexport on explicit class template instantiation
6646  // declarations, except in MinGW mode.
6647  if (ClassExported && !ClassAttr->isInherited() &&
6649  !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6650  Class->dropAttr<DLLExportAttr>();
6651  return;
6652  }
6653 
6654  // Force declaration of implicit members so they can inherit the attribute.
6656 
6657  // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6658  // seem to be true in practice?
6659 
6660  for (Decl *Member : Class->decls()) {
6661  VarDecl *VD = dyn_cast<VarDecl>(Member);
6662  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6663 
6664  // Only methods and static fields inherit the attributes.
6665  if (!VD && !MD)
6666  continue;
6667 
6668  if (MD) {
6669  // Don't process deleted methods.
6670  if (MD->isDeleted())
6671  continue;
6672 
6673  if (MD->isInlined()) {
6674  // MinGW does not import or export inline methods. But do it for
6675  // template instantiations.
6679  continue;
6680 
6681  // MSVC versions before 2015 don't export the move assignment operators
6682  // and move constructor, so don't attempt to import/export them if
6683  // we have a definition.
6684  auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6685  if ((MD->isMoveAssignmentOperator() ||
6686  (Ctor && Ctor->isMoveConstructor())) &&
6687  !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6688  continue;
6689 
6690  // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6691  // operator is exported anyway.
6692  if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6693  (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6694  continue;
6695  }
6696  }
6697 
6698  // Don't apply dllimport attributes to static data members of class template
6699  // instantiations when the attribute is propagated from a derived class.
6700  if (VD && PropagatedImport)
6701  continue;
6702 
6703  if (!cast<NamedDecl>(Member)->isExternallyVisible())
6704  continue;
6705 
6706  if (!getDLLAttr(Member)) {
6707  InheritableAttr *NewAttr = nullptr;
6708 
6709  // Do not export/import inline function when -fno-dllexport-inlines is
6710  // passed. But add attribute for later local static var check.
6711  if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6714  if (ClassExported) {
6715  NewAttr = ::new (getASTContext())
6716  DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6717  } else {
6718  NewAttr = ::new (getASTContext())
6719  DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6720  }
6721  } else {
6722  NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6723  }
6724 
6725  NewAttr->setInherited(true);
6726  Member->addAttr(NewAttr);
6727 
6728  if (MD) {
6729  // Propagate DLLAttr to friend re-declarations of MD that have already
6730  // been constructed.
6731  for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6732  FD = FD->getPreviousDecl()) {
6733  if (FD->getFriendObjectKind() == Decl::FOK_None)
6734  continue;
6735  assert(!getDLLAttr(FD) &&
6736  "friend re-decl should not already have a DLLAttr");
6737  NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6738  NewAttr->setInherited(true);
6739  FD->addAttr(NewAttr);
6740  }
6741  }
6742  }
6743  }
6744 
6745  if (ClassExported)
6746  DelayedDllExportClasses.push_back(Class);
6747 }
6748 
6749 /// Perform propagation of DLL attributes from a derived class to a
6750 /// templated base class for MS compatibility.
6752  CXXRecordDecl *Class, Attr *ClassAttr,
6753  ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6754  if (getDLLAttr(
6755  BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6756  // If the base class template has a DLL attribute, don't try to change it.
6757  return;
6758  }
6759 
6760  auto TSK = BaseTemplateSpec->getSpecializationKind();
6761  if (!getDLLAttr(BaseTemplateSpec) &&
6763  TSK == TSK_ImplicitInstantiation)) {
6764  // The template hasn't been instantiated yet (or it has, but only as an
6765  // explicit instantiation declaration or implicit instantiation, which means
6766  // we haven't codegenned any members yet), so propagate the attribute.
6767  auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6768  NewAttr->setInherited(true);
6769  BaseTemplateSpec->addAttr(NewAttr);
6770 
6771  // If this was an import, mark that we propagated it from a derived class to
6772  // a base class template specialization.
6773  if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6774  ImportAttr->setPropagatedToBaseTemplate();
6775 
6776  // If the template is already instantiated, checkDLLAttributeRedeclaration()
6777  // needs to be run again to work see the new attribute. Otherwise this will
6778  // get run whenever the template is instantiated.
6779  if (TSK != TSK_Undeclared)
6780  checkClassLevelDLLAttribute(BaseTemplateSpec);
6781 
6782  return;
6783  }
6784 
6785  if (getDLLAttr(BaseTemplateSpec)) {
6786  // The template has already been specialized or instantiated with an
6787  // attribute, explicitly or through propagation. We should not try to change
6788  // it.
6789  return;
6790  }
6791 
6792  // The template was previously instantiated or explicitly specialized without
6793  // a dll attribute, It's too late for us to add an attribute, so warn that
6794  // this is unsupported.
6795  Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6796  << BaseTemplateSpec->isExplicitSpecialization();
6797  Diag(ClassAttr->getLocation(), diag::note_attribute);
6798  if (BaseTemplateSpec->isExplicitSpecialization()) {
6799  Diag(BaseTemplateSpec->getLocation(),
6800  diag::note_template_class_explicit_specialization_was_here)
6801  << BaseTemplateSpec;
6802  } else {
6803  Diag(BaseTemplateSpec->getPointOfInstantiation(),
6804  diag::note_template_class_instantiation_was_here)
6805  << BaseTemplateSpec;
6806  }
6807 }
6808 
6809 /// Determine the kind of defaulting that would be done for a given function.
6810 ///
6811 /// If the function is both a default constructor and a copy / move constructor
6812 /// (due to having a default argument for the first parameter), this picks
6813 /// CXXSpecialMemberKind::DefaultConstructor.
6814 ///
6815 /// FIXME: Check that case is properly handled by all callers.
6818  if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6819  if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6820  if (Ctor->isDefaultConstructor())
6822 
6823  if (Ctor->isCopyConstructor())
6825 
6826  if (Ctor->isMoveConstructor())
6828  }
6829 
6830  if (MD->isCopyAssignmentOperator())
6832 
6833  if (MD->isMoveAssignmentOperator())
6835 
6836  if (isa<CXXDestructorDecl>(FD))
6838  }
6839 
6840  switch (FD->getDeclName().getCXXOverloadedOperator()) {
6841  case OO_EqualEqual:
6843 
6844  case OO_ExclaimEqual:
6846 
6847  case OO_Spaceship:
6848  // No point allowing this if <=> doesn't exist in the current language mode.
6849  if (!getLangOpts().CPlusPlus20)
6850  break;
6852 
6853  case OO_Less:
6854  case OO_LessEqual:
6855  case OO_Greater:
6856  case OO_GreaterEqual:
6857  // No point allowing this if <=> doesn't exist in the current language mode.
6858  if (!getLangOpts().CPlusPlus20)
6859  break;
6861 
6862  default:
6863  break;
6864  }
6865 
6866  // Not defaultable.
6867  return DefaultedFunctionKind();
6868 }
6869 
6871  SourceLocation DefaultLoc) {
6873  if (DFK.isComparison())
6874  return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6875 
6876  switch (DFK.asSpecialMember()) {
6878  S.DefineImplicitDefaultConstructor(DefaultLoc,
6879  cast<CXXConstructorDecl>(FD));
6880  break;
6882  S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6883  break;
6885  S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6886  break;
6888  S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6889  break;
6891  S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6892  break;
6894  S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6895  break;
6897  llvm_unreachable("Invalid special member.");
6898  }
6899 }
6900 
6901 /// Determine whether a type is permitted to be passed or returned in
6902 /// registers, per C++ [class.temporary]p3.
6905  if (D->isDependentType() || D->isInvalidDecl())
6906  return false;
6907 
6908  // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6909  // The PS4 platform ABI follows the behavior of Clang 3.2.
6910  if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6911  return !D->hasNonTrivialDestructorForCall() &&
6913 
6914  if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6915  bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6916  bool DtorIsTrivialForCall = false;
6917 
6918  // If a class has at least one eligible, trivial copy constructor, it
6919  // is passed according to the C ABI. Otherwise, it is passed indirectly.
6920  //
6921  // Note: This permits classes with non-trivial copy or move ctors to be
6922  // passed in registers, so long as they *also* have a trivial copy ctor,
6923  // which is non-conforming.
6924  if (D->needsImplicitCopyConstructor()) {
6926  if (D->hasTrivialCopyConstructor())
6927  CopyCtorIsTrivial = true;
6929  CopyCtorIsTrivialForCall = true;
6930  }
6931  } else {
6932  for (const CXXConstructorDecl *CD : D->ctors()) {
6933  if (CD->isCopyConstructor() && !CD->isDeleted() &&
6934  !CD->isIneligibleOrNotSelected()) {
6935  if (CD->isTrivial())
6936  CopyCtorIsTrivial = true;
6937  if (CD->isTrivialForCall())
6938  CopyCtorIsTrivialForCall = true;
6939  }
6940  }
6941  }
6942 
6943  if (D->needsImplicitDestructor()) {
6944  if (!D->defaultedDestructorIsDeleted() &&
6946  DtorIsTrivialForCall = true;
6947  } else if (const auto *DD = D->getDestructor()) {
6948  if (!DD->isDeleted() && DD->isTrivialForCall())
6949  DtorIsTrivialForCall = true;
6950  }
6951 
6952  // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6953  if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6954  return true;
6955 
6956  // If a class has a destructor, we'd really like to pass it indirectly
6957  // because it allows us to elide copies. Unfortunately, MSVC makes that
6958  // impossible for small types, which it will pass in a single register or
6959  // stack slot. Most objects with dtors are large-ish, so handle that early.
6960  // We can't call out all large objects as being indirect because there are
6961  // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6962  // how we pass large POD types.
6963 
6964  // Note: This permits small classes with nontrivial destructors to be
6965  // passed in registers, which is non-conforming.
6966  bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6967  uint64_t TypeSize = isAArch64 ? 128 : 64;
6968 
6969  if (CopyCtorIsTrivial &&
6970  S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6971  return true;
6972  return false;
6973  }
6974 
6975  // Per C++ [class.temporary]p3, the relevant condition is:
6976  // each copy constructor, move constructor, and destructor of X is
6977  // either trivial or deleted, and X has at least one non-deleted copy
6978  // or move constructor
6979  bool HasNonDeletedCopyOrMove = false;
6980 
6981  if (D->needsImplicitCopyConstructor() &&
6984  return false;
6985  HasNonDeletedCopyOrMove = true;
6986  }
6987 
6988  if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6991  return false;
6992  HasNonDeletedCopyOrMove = true;
6993  }
6994 
6997  return false;
6998 
6999  for (const CXXMethodDecl *MD : D->methods()) {
7000  if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
7001  continue;
7002 
7003  auto *CD = dyn_cast<CXXConstructorDecl>(MD);
7004  if (CD && CD->isCopyOrMoveConstructor())
7005  HasNonDeletedCopyOrMove = true;
7006  else if (!isa<CXXDestructorDecl>(MD))
7007  continue;
7008 
7009  if (!MD->isTrivialForCall())
7010  return false;
7011  }
7012 
7013  return HasNonDeletedCopyOrMove;
7014 }
7015 
7016 /// Report an error regarding overriding, along with any relevant
7017 /// overridden methods.
7018 ///
7019 /// \param DiagID the primary error to report.
7020 /// \param MD the overriding method.
7021 static bool
7022 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
7023  llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
7024  bool IssuedDiagnostic = false;
7025  for (const CXXMethodDecl *O : MD->overridden_methods()) {
7026  if (Report(O)) {
7027  if (!IssuedDiagnostic) {
7028  S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7029  IssuedDiagnostic = true;
7030  }
7031  S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7032  }
7033  }
7034  return IssuedDiagnostic;
7035 }
7036 
7037 /// Perform semantic checks on a class definition that has been
7038 /// completing, introducing implicitly-declared members, checking for
7039 /// abstract types, etc.
7040 ///
7041 /// \param S The scope in which the class was parsed. Null if we didn't just
7042 /// parse a class definition.
7043 /// \param Record The completed class.
7045  if (!Record)
7046  return;
7047 
7048  if (Record->isAbstract() && !Record->isInvalidDecl()) {
7049  AbstractUsageInfo Info(*this, Record);
7051  }
7052 
7053  // If this is not an aggregate type and has no user-declared constructor,
7054  // complain about any non-static data members of reference or const scalar
7055  // type, since they will never get initializers.
7056  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
7057  !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
7058  !Record->isLambda()) {
7059  bool Complained = false;
7060  for (const auto *F : Record->fields()) {
7061  if (F->hasInClassInitializer() || F->isUnnamedBitField())
7062  continue;
7063 
7064  if (F->getType()->isReferenceType() ||
7065  (F->getType().isConstQualified() && F->getType()->isScalarType())) {
7066  if (!Complained) {
7067  Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
7068  << llvm::to_underlying(Record->getTagKind()) << Record;
7069  Complained = true;
7070  }
7071 
7072  Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
7073  << F->getType()->isReferenceType()
7074  << F->getDeclName();
7075  }
7076  }
7077  }
7078 
7079  if (Record->getIdentifier()) {
7080  // C++ [class.mem]p13:
7081  // If T is the name of a class, then each of the following shall have a
7082  // name different from T:
7083  // - every member of every anonymous union that is a member of class T.
7084  //
7085  // C++ [class.mem]p14:
7086  // In addition, if class T has a user-declared constructor (12.1), every
7087  // non-static data member of class T shall have a name different from T.
7088  DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
7089  for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
7090  ++I) {
7091  NamedDecl *D = (*I)->getUnderlyingDecl();
7092  if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
7093  Record->hasUserDeclaredConstructor()) ||
7094  isa<IndirectFieldDecl>(D)) {
7095  Diag((*I)->getLocation(), diag::err_member_name_of_class)
7096  << D->getDeclName();
7097  break;
7098  }
7099  }
7100  }
7101 
7102  // Warn if the class has virtual methods but non-virtual public destructor.
7103  if (Record->isPolymorphic() && !Record->isDependentType()) {
7104  CXXDestructorDecl *dtor = Record->getDestructor();
7105  if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
7106  !Record->hasAttr<FinalAttr>())
7107  Diag(dtor ? dtor->getLocation() : Record->getLocation(),
7108  diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
7109  }
7110 
7111  if (Record->isAbstract()) {
7112  if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
7113  Diag(Record->getLocation(), diag::warn_abstract_final_class)
7114  << FA->isSpelledAsSealed();
7116  }
7117  }
7118 
7119  // Warn if the class has a final destructor but is not itself marked final.
7120  if (!Record->hasAttr<FinalAttr>()) {
7121  if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
7122  if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
7123  Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
7124  << FA->isSpelledAsSealed()
7126  getLocForEndOfToken(Record->getLocation()),
7127  (FA->isSpelledAsSealed() ? " sealed" : " final"));
7128  Diag(Record->getLocation(),
7129  diag::note_final_dtor_non_final_class_silence)
7130  << Context.getRecordType(Record) << FA->isSpelledAsSealed();
7131  }
7132  }
7133  }
7134 
7135  // See if trivial_abi has to be dropped.
7136  if (Record->hasAttr<TrivialABIAttr>())
7138 
7139  // Set HasTrivialSpecialMemberForCall if the record has attribute
7140  // "trivial_abi".
7141  bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7142 
7143  if (HasTrivialABI)
7144  Record->setHasTrivialSpecialMemberForCall();
7145 
7146  // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7147  // We check these last because they can depend on the properties of the
7148  // primary comparison functions (==, <=>).
7149  llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7150 
7151  // Perform checks that can't be done until we know all the properties of a
7152  // member function (whether it's defaulted, deleted, virtual, overriding,
7153  // ...).
7154  auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7155  // A static function cannot override anything.
7156  if (MD->getStorageClass() == SC_Static) {
7157  if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
7158  [](const CXXMethodDecl *) { return true; }))
7159  return;
7160  }
7161 
7162  // A deleted function cannot override a non-deleted function and vice
7163  // versa.
7164  if (ReportOverrides(*this,
7165  MD->isDeleted() ? diag::err_deleted_override
7166  : diag::err_non_deleted_override,
7167  MD, [&](const CXXMethodDecl *V) {
7168  return MD->isDeleted() != V->isDeleted();
7169  })) {
7170  if (MD->isDefaulted() && MD->isDeleted())
7171  // Explain why this defaulted function was deleted.
7173  return;
7174  }
7175 
7176  // A consteval function cannot override a non-consteval function and vice
7177  // versa.
7178  if (ReportOverrides(*this,
7179  MD->isConsteval() ? diag::err_consteval_override
7180  : diag::err_non_consteval_override,
7181  MD, [&](const CXXMethodDecl *V) {
7182  return MD->isConsteval() != V->isConsteval();
7183  })) {
7184  if (MD->isDefaulted() && MD->isDeleted())
7185  // Explain why this defaulted function was deleted.
7187  return;
7188  }
7189  };
7190 
7191  auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7192  if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7193  return false;
7194 
7198  DefaultedSecondaryComparisons.push_back(FD);
7199  return true;
7200  }
7201 
7203  return false;
7204  };
7205 
7206  auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7207  // Check whether the explicitly-defaulted members are valid.
7208  bool Incomplete = CheckForDefaultedFunction(M);
7209 
7210  // Skip the rest of the checks for a member of a dependent class.
7211  if (Record->isDependentType())
7212  return;
7213 
7214  // For an explicitly defaulted or deleted special member, we defer
7215  // determining triviality until the class is complete. That time is now!
7217  if (!M->isImplicit() && !M->isUserProvided()) {
7218  if (CSM != CXXSpecialMemberKind::Invalid) {
7219  M->setTrivial(SpecialMemberIsTrivial(M, CSM));
7220  // Inform the class that we've finished declaring this member.
7221  Record->finishedDefaultedOrDeletedMember(M);
7222  M->setTrivialForCall(
7223  HasTrivialABI ||
7225  Record->setTrivialForCallFlags(M);
7226  }
7227  }
7228 
7229  // Set triviality for the purpose of calls if this is a user-provided
7230  // copy/move constructor or destructor.
7234  M->isUserProvided()) {
7235  M->setTrivialForCall(HasTrivialABI);
7236  Record->setTrivialForCallFlags(M);
7237  }
7238 
7239  if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7240  M->hasAttr<DLLExportAttr>()) {
7241  if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
7242  M->isTrivial() &&
7246  M->dropAttr<DLLExportAttr>();
7247 
7248  if (M->hasAttr<DLLExportAttr>()) {
7249  // Define after any fields with in-class initializers have been parsed.
7250  DelayedDllExportMemberFunctions.push_back(M);
7251  }
7252  }
7253 
7254  // Define defaulted constexpr virtual functions that override a base class
7255  // function right away.
7256  // FIXME: We can defer doing this until the vtable is marked as used.
7257  if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7258  M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
7259  DefineDefaultedFunction(*this, M, M->getLocation());
7260 
7261  if (!Incomplete)
7262  CheckCompletedMemberFunction(M);
7263  };
7264 
7265  // Check the destructor before any other member function. We need to
7266  // determine whether it's trivial in order to determine whether the claas
7267  // type is a literal type, which is a prerequisite for determining whether
7268  // other special member functions are valid and whether they're implicitly
7269  // 'constexpr'.
7270  if (CXXDestructorDecl *Dtor = Record->getDestructor())
7271  CompleteMemberFunction(Dtor);
7272 
7273  bool HasMethodWithOverrideControl = false,
7274  HasOverridingMethodWithoutOverrideControl = false;
7275  for (auto *D : Record->decls()) {
7276  if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
7277  // FIXME: We could do this check for dependent types with non-dependent
7278  // bases.
7279  if (!Record->isDependentType()) {
7280  // See if a method overloads virtual methods in a base
7281  // class without overriding any.
7282  if (!M->isStatic())
7284  if (M->hasAttr<OverrideAttr>())
7285  HasMethodWithOverrideControl = true;
7286  else if (M->size_overridden_methods() > 0)
7287  HasOverridingMethodWithoutOverrideControl = true;
7288  }
7289 
7290  if (!isa<CXXDestructorDecl>(M))
7291  CompleteMemberFunction(M);
7292  } else if (auto *F = dyn_cast<FriendDecl>(D)) {
7293  CheckForDefaultedFunction(
7294  dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7295  }
7296  }
7297 
7298  if (HasOverridingMethodWithoutOverrideControl) {
7299  bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7300  for (auto *M : Record->methods())
7301  DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7302  }
7303 
7304  // Check the defaulted secondary comparisons after any other member functions.
7305  for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7307 
7308  // If this is a member function, we deferred checking it until now.
7309  if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7310  CheckCompletedMemberFunction(MD);
7311  }
7312 
7313  // ms_struct is a request to use the same ABI rules as MSVC. Check
7314  // whether this class uses any C++ features that are implemented
7315  // completely differently in MSVC, and if so, emit a diagnostic.
7316  // That diagnostic defaults to an error, but we allow projects to
7317  // map it down to a warning (or ignore it). It's a fairly common
7318  // practice among users of the ms_struct pragma to mass-annotate
7319  // headers, sweeping up a bunch of types that the project doesn't
7320  // really rely on MSVC-compatible layout for. We must therefore
7321  // support "ms_struct except for C++ stuff" as a secondary ABI.
7322  // Don't emit this diagnostic if the feature was enabled as a
7323  // language option (as opposed to via a pragma or attribute), as
7324  // the option -mms-bitfields otherwise essentially makes it impossible
7325  // to build C++ code, unless this diagnostic is turned off.
7326  if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
7327  (Record->isPolymorphic() || Record->getNumBases())) {
7328  Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7329  }
7330 
7333 
7334  bool ClangABICompat4 =
7335  Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7337  Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7338  bool CanPass = canPassInRegisters(*this, Record, CCK);
7339 
7340  // Do not change ArgPassingRestrictions if it has already been set to
7341  // RecordArgPassingKind::CanNeverPassInRegs.
7342  if (Record->getArgPassingRestrictions() !=
7344  Record->setArgPassingRestrictions(
7347 
7348  // If canPassInRegisters returns true despite the record having a non-trivial
7349  // destructor, the record is destructed in the callee. This happens only when
7350  // the record or one of its subobjects has a field annotated with trivial_abi
7351  // or a field qualified with ObjC __strong/__weak.
7353  Record->setParamDestroyedInCallee(true);
7354  else if (Record->hasNonTrivialDestructor())
7355  Record->setParamDestroyedInCallee(CanPass);
7356 
7357  if (getLangOpts().ForceEmitVTables) {
7358  // If we want to emit all the vtables, we need to mark it as used. This
7359  // is especially required for cases like vtable assumption loads.
7360  MarkVTableUsed(Record->getInnerLocStart(), Record);
7361  }
7362 
7363  if (getLangOpts().CUDA) {
7364  if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7366  else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7368  }
7369 }
7370 
7371 /// Look up the special member function that would be called by a special
7372 /// member function for a subobject of class type.
7373 ///
7374 /// \param Class The class type of the subobject.
7375 /// \param CSM The kind of special member function.
7376 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7377 /// \param ConstRHS True if this is a copy operation with a const object
7378 /// on its RHS, that is, if the argument to the outer special member
7379 /// function is 'const' and this is not a field marked 'mutable'.
7382  CXXSpecialMemberKind CSM, unsigned FieldQuals,
7383  bool ConstRHS) {
7384  unsigned LHSQuals = 0;
7387  LHSQuals = FieldQuals;
7388 
7389  unsigned RHSQuals = FieldQuals;
7392  RHSQuals = 0;
7393  else if (ConstRHS)
7394  RHSQuals |= Qualifiers::Const;
7395 
7396  return S.LookupSpecialMember(Class, CSM,
7397  RHSQuals & Qualifiers::Const,
7398  RHSQuals & Qualifiers::Volatile,
7399  false,
7400  LHSQuals & Qualifiers::Const,
7401  LHSQuals & Qualifiers::Volatile);
7402 }
7403 
7405  Sema &S;
7406  SourceLocation UseLoc;
7407 
7408  /// A mapping from the base classes through which the constructor was
7409  /// inherited to the using shadow declaration in that base class (or a null
7410  /// pointer if the constructor was declared in that base class).
7411  llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7412  InheritedFromBases;
7413 
7414 public:
7417  : S(S), UseLoc(UseLoc) {
7418  bool DiagnosedMultipleConstructedBases = false;
7419  CXXRecordDecl *ConstructedBase = nullptr;
7420  BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7421 
7422  // Find the set of such base class subobjects and check that there's a
7423  // unique constructed subobject.
7424  for (auto *D : Shadow->redecls()) {
7425  auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7426  auto *DNominatedBase = DShadow->getNominatedBaseClass();
7427  auto *DConstructedBase = DShadow->getConstructedBaseClass();
7428 
7429  InheritedFromBases.insert(
7430  std::make_pair(DNominatedBase->getCanonicalDecl(),
7431  DShadow->getNominatedBaseClassShadowDecl()));
7432  if (DShadow->constructsVirtualBase())
7433  InheritedFromBases.insert(
7434  std::make_pair(DConstructedBase->getCanonicalDecl(),
7435  DShadow->getConstructedBaseClassShadowDecl()));
7436  else
7437  assert(DNominatedBase == DConstructedBase);
7438 
7439  // [class.inhctor.init]p2:
7440  // If the constructor was inherited from multiple base class subobjects
7441  // of type B, the program is ill-formed.
7442  if (!ConstructedBase) {
7443  ConstructedBase = DConstructedBase;
7444  ConstructedBaseIntroducer = D->getIntroducer();
7445  } else if (ConstructedBase != DConstructedBase &&
7446  !Shadow->isInvalidDecl()) {
7447  if (!DiagnosedMultipleConstructedBases) {
7448  S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7449  << Shadow->getTargetDecl();
7450  S.Diag(ConstructedBaseIntroducer->getLocation(),
7451  diag::note_ambiguous_inherited_constructor_using)
7452  << ConstructedBase;
7453  DiagnosedMultipleConstructedBases = true;
7454  }
7455  S.Diag(D->getIntroducer()->getLocation(),
7456  diag::note_ambiguous_inherited_constructor_using)
7457  << DConstructedBase;
7458  }
7459  }
7460 
7461  if (DiagnosedMultipleConstructedBases)
7462  Shadow->setInvalidDecl();
7463  }
7464 
7465  /// Find the constructor to use for inherited construction of a base class,
7466  /// and whether that base class constructor inherits the constructor from a
7467  /// virtual base class (in which case it won't actually invoke it).
7468  std::pair<CXXConstructorDecl *, bool>
7470  auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7471  if (It == InheritedFromBases.end())
7472  return std::make_pair(nullptr, false);
7473 
7474  // This is an intermediary class.
7475  if (It->second)
7476  return std::make_pair(
7477  S.findInheritingConstructor(UseLoc, Ctor, It->second),
7478  It->second->constructsVirtualBase());
7479 
7480  // This is the base class from which the constructor was inherited.
7481  return std::make_pair(Ctor, false);
7482  }
7483 };
7484 
7485 /// Is the special member function which would be selected to perform the
7486 /// specified operation on the specified class type a constexpr constructor?
7488  Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7489  bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7490  Sema::InheritedConstructorInfo *Inherited = nullptr) {
7491  // Suppress duplicate constraint checking here, in case a constraint check
7492  // caused us to decide to do this. Any truely recursive checks will get
7493  // caught during these checks anyway.
7495 
7496  // If we're inheriting a constructor, see if we need to call it for this base
7497  // class.
7498  if (InheritedCtor) {
7500  auto BaseCtor =
7501  Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7502  if (BaseCtor)
7503  return BaseCtor->isConstexpr();
7504  }
7505 
7507  return ClassDecl->hasConstexprDefaultConstructor();
7509  return ClassDecl->hasConstexprDestructor();
7510 
7512  lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7513  if (!SMOR.getMethod())
7514  // A constructor we wouldn't select can't be "involved in initializing"
7515  // anything.
7516  return true;
7517  return SMOR.getMethod()->isConstexpr();
7518 }
7519 
7520 /// Determine whether the specified special member function would be constexpr
7521 /// if it were implicitly defined.
7523  Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7524  CXXConstructorDecl *InheritedCtor = nullptr,
7525  Sema::InheritedConstructorInfo *Inherited = nullptr) {
7526  if (!S.getLangOpts().CPlusPlus11)
7527  return false;
7528 
7529  // C++11 [dcl.constexpr]p4:
7530  // In the definition of a constexpr constructor [...]
7531  bool Ctor = true;
7532  switch (CSM) {
7534  if (Inherited)
7535  break;
7536  // Since default constructor lookup is essentially trivial (and cannot
7537  // involve, for instance, template instantiation), we compute whether a
7538  // defaulted default constructor is constexpr directly within CXXRecordDecl.
7539  //
7540  // This is important for performance; we need to know whether the default
7541  // constructor is constexpr to determine whether the type is a literal type.
7542  return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7543 
7546  // For copy or move constructors, we need to perform overload resolution.
7547  break;
7548 
7551  if (!S.getLangOpts().CPlusPlus14)
7552  return false;
7553  // In C++1y, we need to perform overload resolution.
7554  Ctor = false;
7555  break;
7556 
7558  return ClassDecl->defaultedDestructorIsConstexpr();
7559 
7561  return false;
7562  }
7563 
7564  // -- if the class is a non-empty union, or for each non-empty anonymous
7565  // union member of a non-union class, exactly one non-static data member
7566  // shall be initialized; [DR1359]
7567  //
7568  // If we squint, this is guaranteed, since exactly one non-static data member
7569  // will be initialized (if the constructor isn't deleted), we just don't know
7570  // which one.
7571  if (Ctor && ClassDecl->isUnion())
7573  ? ClassDecl->hasInClassInitializer() ||
7574  !ClassDecl->hasVariantMembers()
7575  : true;
7576 
7577  // -- the class shall not have any virtual base classes;
7578  if (Ctor && ClassDecl->getNumVBases())
7579  return false;
7580 
7581  // C++1y [class.copy]p26:
7582  // -- [the class] is a literal type, and
7583  if (!Ctor && !ClassDecl->isLiteral() && !S.getLangOpts().CPlusPlus23)
7584  return false;
7585 
7586  // -- every constructor involved in initializing [...] base class
7587  // sub-objects shall be a constexpr constructor;
7588  // -- the assignment operator selected to copy/move each direct base
7589  // class is a constexpr function, and
7590  if (!S.getLangOpts().CPlusPlus23) {
7591  for (const auto &B : ClassDecl->bases()) {
7592  const RecordType *BaseType = B.getType()->getAs<RecordType>();
7593  if (!BaseType)
7594  continue;
7595  CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7596  if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7597  InheritedCtor, Inherited))
7598  return false;
7599  }
7600  }
7601 
7602  // -- every constructor involved in initializing non-static data members
7603  // [...] shall be a constexpr constructor;
7604  // -- every non-static data member and base class sub-object shall be
7605  // initialized
7606  // -- for each non-static data member of X that is of class type (or array
7607  // thereof), the assignment operator selected to copy/move that member is
7608  // a constexpr function
7609  if (!S.getLangOpts().CPlusPlus23) {
7610  for (const auto *F : ClassDecl->fields()) {
7611  if (F->isInvalidDecl())
7612  continue;
7614  F->hasInClassInitializer())
7615  continue;
7616  QualType BaseType = S.Context.getBaseElementType(F->getType());
7617  if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7618  CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7619  if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7620  BaseType.getCVRQualifiers(),
7621  ConstArg && !F->isMutable()))
7622  return false;
7623  } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7624  return false;
7625  }
7626  }
7627  }
7628 
7629  // All OK, it's constexpr!
7630  return true;
7631 }
7632 
7633 namespace {
7634 /// RAII object to register a defaulted function as having its exception
7635 /// specification computed.
7636 struct ComputingExceptionSpec {
7637  Sema &S;
7638 
7639  ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7640  : S(S) {
7643  Ctx.PointOfInstantiation = Loc;
7644  Ctx.Entity = FD;
7645  S.pushCodeSynthesisContext(Ctx);
7646  }
7647  ~ComputingExceptionSpec() {
7649  }
7650 };
7651 }
7652 
7655  CXXMethodDecl *MD,
7658 
7661  FunctionDecl *FD,
7663 
7666  auto DFK = S.getDefaultedFunctionKind(FD);
7667  if (DFK.isSpecialMember())
7669  S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7670  if (DFK.isComparison())
7671  return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7672  DFK.asComparison());
7673 
7674  auto *CD = cast<CXXConstructorDecl>(FD);
7675  assert(CD->getInheritedConstructor() &&
7676  "only defaulted functions and inherited constructors have implicit "
7677  "exception specs");
7679  S, Loc, CD->getInheritedConstructor().getShadowDecl());
7681  S, Loc, CD, CXXSpecialMemberKind::DefaultConstructor, &ICI);
7682 }
7683 
7685  CXXMethodDecl *MD) {
7687 
7688  // Build an exception specification pointing back at this member.
7690  EPI.ExceptionSpec.SourceDecl = MD;
7691 
7692  // Set the calling convention to the default for C++ instance methods.
7693  EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7694  S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7695  /*IsCXXMethod=*/true));
7696  return EPI;
7697 }
7698 
7700  const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7701  if (FPT->getExceptionSpecType() != EST_Unevaluated)
7702  return;
7703 
7704  // Evaluate the exception specification.
7705  auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7706  auto ESI = IES.getExceptionSpec();
7707 
7708  // Update the type of the special member to use it.
7709  UpdateExceptionSpec(FD, ESI);
7710 }
7711 
7713  assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7714 
7716  if (!DefKind) {
7717  assert(FD->getDeclContext()->isDependentContext());
7718  return;
7719  }
7720 
7721  if (DefKind.isComparison())
7722  UnusedPrivateFields.clear();
7723 
7724  if (DefKind.isSpecialMember()
7725  ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7726  DefKind.asSpecialMember(),
7727  FD->getDefaultLoc())
7729  FD->setInvalidDecl();
7730 }
7731 
7734  SourceLocation DefaultLoc) {
7735  CXXRecordDecl *RD = MD->getParent();
7736 
7737  assert(MD->isExplicitlyDefaulted() && CSM != CXXSpecialMemberKind::Invalid &&
7738  "not an explicitly-defaulted special member");
7739 
7740  // Defer all checking for special members of a dependent type.
7741  if (RD->isDependentType())
7742  return false;
7743 
7744  // Whether this was the first-declared instance of the constructor.
7745  // This affects whether we implicitly add an exception spec and constexpr.
7746  bool First = MD == MD->getCanonicalDecl();
7747 
7748  bool HadError = false;
7749 
7750  // C++11 [dcl.fct.def.default]p1:
7751  // A function that is explicitly defaulted shall
7752  // -- be a special member function [...] (checked elsewhere),
7753  // -- have the same type (except for ref-qualifiers, and except that a
7754  // copy operation can take a non-const reference) as an implicit
7755  // declaration, and
7756  // -- not have default arguments.
7757  // C++2a changes the second bullet to instead delete the function if it's
7758  // defaulted on its first declaration, unless it's "an assignment operator,
7759  // and its return type differs or its parameter type is not a reference".
7760  bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7761  bool ShouldDeleteForTypeMismatch = false;
7762  unsigned ExpectedParams = 1;
7765  ExpectedParams = 0;
7766  if (MD->getNumExplicitParams() != ExpectedParams) {
7767  // This checks for default arguments: a copy or move constructor with a
7768  // default argument is classified as a default constructor, and assignment
7769  // operations and destructors can't have default arguments.
7770  Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7771  << llvm::to_underlying(CSM) << MD->getSourceRange();
7772  HadError = true;
7773  } else if (MD->isVariadic()) {
7774  if (DeleteOnTypeMismatch)
7775  ShouldDeleteForTypeMismatch = true;
7776  else {
7777  Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7778  << llvm::to_underlying(CSM) << MD->getSourceRange();
7779  HadError = true;
7780  }
7781  }
7782 
7784 
7785  bool CanHaveConstParam = false;
7787  CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7788  else if (CSM == CXXSpecialMemberKind::CopyAssignment)
7789  CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7790 
7791  QualType ReturnType = Context.VoidTy;
7794  // Check for return type matching.
7795  ReturnType = Type->getReturnType();
7796  QualType ThisType = MD->getFunctionObjectParameterType();
7797 
7798  QualType DeclType = Context.getTypeDeclType(RD);
7800  DeclType, nullptr);
7801  DeclType = Context.getAddrSpaceQualType(
7802  DeclType, ThisType.getQualifiers().getAddressSpace());
7803  QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7804 
7805  if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7806  Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7808  << ExpectedReturnType;
7809  HadError = true;
7810  }
7811 
7812  // A defaulted special member cannot have cv-qualifiers.
7813  if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7814  if (DeleteOnTypeMismatch)
7815  ShouldDeleteForTypeMismatch = true;
7816  else {
7817  Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7819  << getLangOpts().CPlusPlus14;
7820  HadError = true;
7821  }
7822  }
7823  // [C++23][dcl.fct.def.default]/p2.2
7824  // if F2 has an implicit object parameter of type “reference to C”,
7825  // F1 may be an explicit object member function whose explicit object
7826  // parameter is of (possibly different) type “reference to C”,
7827  // in which case the type of F1 would differ from the type of F2
7828  // in that the type of F1 has an additional parameter;
7829  if (!Context.hasSameType(
7831  Context.getRecordType(RD))) {
7832  if (DeleteOnTypeMismatch)
7833  ShouldDeleteForTypeMismatch = true;
7834  else {
7835  Diag(MD->getLocation(),
7836  diag::err_defaulted_special_member_explicit_object_mismatch)
7837  << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
7838  << MD->getSourceRange();
7839  HadError = true;
7840  }
7841  }
7842  }
7843 
7844  // Check for parameter type matching.
7845  QualType ArgType =
7846  ExpectedParams
7847  ? Type->getParamType(MD->isExplicitObjectMemberFunction() ? 1 : 0)
7848  : QualType();
7849  bool HasConstParam = false;
7850  if (ExpectedParams && ArgType->isReferenceType()) {
7851  // Argument must be reference to possibly-const T.
7852  QualType ReferentType = ArgType->getPointeeType();
7853  HasConstParam = ReferentType.isConstQualified();
7854 
7855  if (ReferentType.isVolatileQualified()) {
7856  if (DeleteOnTypeMismatch)
7857  ShouldDeleteForTypeMismatch = true;
7858  else {
7859  Diag(MD->getLocation(),
7860  diag::err_defaulted_special_member_volatile_param)
7861  << llvm::to_underlying(CSM);
7862  HadError = true;
7863  }
7864  }
7865 
7866  if (HasConstParam && !CanHaveConstParam) {
7867  if (DeleteOnTypeMismatch)
7868  ShouldDeleteForTypeMismatch = true;
7869  else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
7871  Diag(MD->getLocation(),
7872  diag::err_defaulted_special_member_copy_const_param)
7874  // FIXME: Explain why this special member can't be const.
7875  HadError = true;
7876  } else {
7877  Diag(MD->getLocation(),
7878  diag::err_defaulted_special_member_move_const_param)
7880  HadError = true;
7881  }
7882  }
7883  } else if (ExpectedParams) {
7884  // A copy assignment operator can take its argument by value, but a
7885  // defaulted one cannot.
7886  assert(CSM == CXXSpecialMemberKind::CopyAssignment &&
7887  "unexpected non-ref argument");
7888  Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7889  HadError = true;
7890  }
7891 
7892  // C++11 [dcl.fct.def.default]p2:
7893  // An explicitly-defaulted function may be declared constexpr only if it
7894  // would have been implicitly declared as constexpr,
7895  // Do not apply this rule to members of class templates, since core issue 1358
7896  // makes such functions always instantiate to constexpr functions. For
7897  // functions which cannot be constexpr (for non-constructors in C++11 and for
7898  // destructors in C++14 and C++17), this is checked elsewhere.
7899  //
7900  // FIXME: This should not apply if the member is deleted.
7901  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7902  HasConstParam);
7903 
7904  // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
7905  // If the instantiated template specialization of a constexpr function
7906  // template or member function of a class template would fail to satisfy
7907  // the requirements for a constexpr function or constexpr constructor, that
7908  // specialization is still a constexpr function or constexpr constructor,
7909  // even though a call to such a function cannot appear in a constant
7910  // expression.
7911  if (MD->isTemplateInstantiation() && MD->isConstexpr())
7912  Constexpr = true;
7913 
7914  if ((getLangOpts().CPlusPlus20 ||
7915  (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7916  : isa<CXXConstructorDecl>(MD))) &&
7917  MD->isConstexpr() && !Constexpr &&
7919  if (!MD->isConsteval() && RD->getNumVBases()) {
7920  Diag(MD->getBeginLoc(),
7921  diag::err_incorrect_defaulted_constexpr_with_vb)
7922  << llvm::to_underlying(CSM);
7923  for (const auto &I : RD->vbases())
7924  Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here);
7925  } else {
7926  Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr)
7927  << llvm::to_underlying(CSM) << MD->isConsteval();
7928  }
7929  HadError = true;
7930  // FIXME: Explain why the special member can't be constexpr.
7931  }
7932 
7933  if (First) {
7934  // C++2a [dcl.fct.def.default]p3:
7935  // If a function is explicitly defaulted on its first declaration, it is
7936  // implicitly considered to be constexpr if the implicit declaration
7937  // would be.
7942 
7943  if (!Type->hasExceptionSpec()) {
7944  // C++2a [except.spec]p3:
7945  // If a declaration of a function does not have a noexcept-specifier
7946  // [and] is defaulted on its first declaration, [...] the exception
7947  // specification is as specified below
7948  FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7950  EPI.ExceptionSpec.SourceDecl = MD;
7951  MD->setType(
7952  Context.getFunctionType(ReturnType, Type->getParamTypes(), EPI));
7953  }
7954  }
7955 
7956  if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7957  if (First) {
7958  SetDeclDeleted(MD, MD->getLocation());
7959  if (!inTemplateInstantiation() && !HadError) {
7960  Diag(MD->getLocation(), diag::warn_defaulted_method_deleted)
7961  << llvm::to_underlying(CSM);
7962  if (ShouldDeleteForTypeMismatch) {
7963  Diag(MD->getLocation(), diag::note_deleted_type_mismatch)
7964  << llvm::to_underlying(CSM);
7965  } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,
7966  /*Diagnose*/ true) &&
7967  DefaultLoc.isValid()) {
7968  Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
7969  << FixItHint::CreateReplacement(DefaultLoc, "delete");
7970  }
7971  }
7972  if (ShouldDeleteForTypeMismatch && !HadError) {
7973  Diag(MD->getLocation(),
7974  diag::warn_cxx17_compat_defaulted_method_type_mismatch)
7975  << llvm::to_underlying(CSM);
7976  }
7977  } else {
7978  // C++11 [dcl.fct.def.default]p4:
7979  // [For a] user-provided explicitly-defaulted function [...] if such a
7980  // function is implicitly defined as deleted, the program is ill-formed.
7981  Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
7982  << llvm::to_underlying(CSM);
7983  assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7984  ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7985  HadError = true;
7986  }
7987  }
7988 
7989  return HadError;
7990 }
7991 
7992 namespace {
7993 /// Helper class for building and checking a defaulted comparison.
7994 ///
7995 /// Defaulted functions are built in two phases:
7996 ///
7997 /// * First, the set of operations that the function will perform are
7998 /// identified, and some of them are checked. If any of the checked
7999 /// operations is invalid in certain ways, the comparison function is
8000 /// defined as deleted and no body is built.
8001 /// * Then, if the function is not defined as deleted, the body is built.
8002 ///
8003 /// This is accomplished by performing two visitation steps over the eventual
8004 /// body of the function.
8005 template<typename Derived, typename ResultList, typename Result,
8006  typename Subobject>
8007 class DefaultedComparisonVisitor {
8008 public:
8010 
8011  DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8013  : S(S), RD(RD), FD(FD), DCK(DCK) {
8014  if (auto *Info = FD->getDefalutedOrDeletedInfo()) {
8015  // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
8016  // UnresolvedSet to avoid this copy.
8017  Fns.assign(Info->getUnqualifiedLookups().begin(),
8018  Info->getUnqualifiedLookups().end());
8019  }
8020  }
8021 
8022  ResultList visit() {
8023  // The type of an lvalue naming a parameter of this function.
8024  QualType ParamLvalType =
8026 
8027  ResultList Results;
8028 
8029  switch (DCK) {
8031  llvm_unreachable("not a defaulted comparison");
8032 
8035  getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
8036  return Results;
8037 
8040  Results.add(getDerived().visitExpandedSubobject(
8041  ParamLvalType, getDerived().getCompleteObject()));
8042  return Results;
8043  }
8044  llvm_unreachable("");
8045  }
8046 
8047 protected:
8048  Derived &getDerived() { return static_cast<Derived&>(*this); }
8049 
8050  /// Visit the expanded list of subobjects of the given type, as specified in
8051  /// C++2a [class.compare.default].
8052  ///
8053  /// \return \c true if the ResultList object said we're done, \c false if not.
8054  bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
8055  Qualifiers Quals) {
8056  // C++2a [class.compare.default]p4:
8057  // The direct base class subobjects of C
8058  for (CXXBaseSpecifier &Base : Record->bases())
8059  if (Results.add(getDerived().visitSubobject(
8060  S.Context.getQualifiedType(Base.getType(), Quals),
8061  getDerived().getBase(&Base))))
8062  return true;
8063 
8064  // followed by the non-static data members of C
8065  for (FieldDecl *Field : Record->fields()) {
8066  // C++23 [class.bit]p2:
8067  // Unnamed bit-fields are not members ...
8068  if (Field->isUnnamedBitField())
8069  continue;
8070  // Recursively expand anonymous structs.
8071  if (Field->isAnonymousStructOrUnion()) {
8072  if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
8073  Quals))
8074  return true;
8075  continue;
8076  }
8077 
8078  // Figure out the type of an lvalue denoting this field.
8079  Qualifiers FieldQuals = Quals;
8080  if (Field->isMutable())
8081  FieldQuals.removeConst();
8082  QualType FieldType =
8083  S.Context.getQualifiedType(Field->getType(), FieldQuals);
8084 
8085  if (Results.add(getDerived().visitSubobject(
8086  FieldType, getDerived().getField(Field))))
8087  return true;
8088  }
8089 
8090  // form a list of subobjects.
8091  return false;
8092  }
8093 
8094  Result visitSubobject(QualType Type, Subobject Subobj) {
8095  // In that list, any subobject of array type is recursively expanded
8096  const ArrayType *AT = S.Context.getAsArrayType(Type);
8097  if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
8098  return getDerived().visitSubobjectArray(CAT->getElementType(),
8099  CAT->getSize(), Subobj);
8100  return getDerived().visitExpandedSubobject(Type, Subobj);
8101  }
8102 
8103  Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
8104  Subobject Subobj) {
8105  return getDerived().visitSubobject(Type, Subobj);
8106  }
8107 
8108 protected:
8109  Sema &S;
8110  CXXRecordDecl *RD;
8111  FunctionDecl *FD;
8113  UnresolvedSet<16> Fns;
8114 };
8115 
8116 /// Information about a defaulted comparison, as determined by
8117 /// DefaultedComparisonAnalyzer.
8118 struct DefaultedComparisonInfo {
8119  bool Deleted = false;
8120  bool Constexpr = true;
8122 
8123  static DefaultedComparisonInfo deleted() {
8124  DefaultedComparisonInfo Deleted;
8125  Deleted.Deleted = true;
8126  return Deleted;
8127  }
8128 
8129  bool add(const DefaultedComparisonInfo &R) {
8130  Deleted |= R.Deleted;
8131  Constexpr &= R.Constexpr;
8132  Category = commonComparisonType(Category, R.Category);
8133  return Deleted;
8134  }
8135 };
8136 
8137 /// An element in the expanded list of subobjects of a defaulted comparison, as
8138 /// specified in C++2a [class.compare.default]p4.
8139 struct DefaultedComparisonSubobject {
8140  enum { CompleteObject, Member, Base } Kind;
8141  NamedDecl *Decl;
8142  SourceLocation Loc;
8143 };
8144 
8145 /// A visitor over the notional body of a defaulted comparison that determines
8146 /// whether that body would be deleted or constexpr.
8147 class DefaultedComparisonAnalyzer
8148  : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8149  DefaultedComparisonInfo,
8150  DefaultedComparisonInfo,
8151  DefaultedComparisonSubobject> {
8152 public:
8153  enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8154 
8155 private:
8156  DiagnosticKind Diagnose;
8157 
8158 public:
8159  using Base = DefaultedComparisonVisitor;
8160  using Result = DefaultedComparisonInfo;
8161  using Subobject = DefaultedComparisonSubobject;
8162 
8163  friend Base;
8164 
8165  DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8167  DiagnosticKind Diagnose = NoDiagnostics)
8168  : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8169 
8170  Result visit() {
8171  if ((DCK == DefaultedComparisonKind::Equal ||
8173  RD->hasVariantMembers()) {
8174  // C++2a [class.compare.default]p2 [P2002R0]:
8175  // A defaulted comparison operator function for class C is defined as
8176  // deleted if [...] C has variant members.
8177  if (Diagnose == ExplainDeleted) {
8178  S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
8179  << FD << RD->isUnion() << RD;
8180  }
8181  return Result::deleted();
8182  }
8183 
8184  return Base::visit();
8185  }
8186 
8187 private:
8188  Subobject getCompleteObject() {
8189  return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
8190  }
8191 
8192  Subobject getBase(CXXBaseSpecifier *Base) {
8193  return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
8194  Base->getBaseTypeLoc()};
8195  }
8196 
8197  Subobject getField(FieldDecl *Field) {
8198  return Subobject{Subobject::Member, Field, Field->getLocation()};
8199  }
8200 
8201  Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8202  // C++2a [class.compare.default]p2 [P2002R0]:
8203  // A defaulted <=> or == operator function for class C is defined as
8204  // deleted if any non-static data member of C is of reference type
8205  if (Type->isReferenceType()) {
8206  if (Diagnose == ExplainDeleted) {
8207  S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
8208  << FD << RD;
8209  }
8210  return Result::deleted();
8211  }
8212 
8213  // [...] Let xi be an lvalue denoting the ith element [...]
8215  Expr *Args[] = {&Xi, &Xi};
8216 
8217  // All operators start by trying to apply that same operator recursively.
8219  assert(OO != OO_None && "not an overloaded operator!");
8220  return visitBinaryOperator(OO, Args, Subobj);
8221  }
8222 
8223  Result
8224  visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8225  Subobject Subobj,
8226  OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8227  // Note that there is no need to consider rewritten candidates here if
8228  // we've already found there is no viable 'operator<=>' candidate (and are
8229  // considering synthesizing a '<=>' from '==' and '<').
8230  OverloadCandidateSet CandidateSet(
8233  OO, FD->getLocation(),
8234  /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8235 
8236  /// C++2a [class.compare.default]p1 [P2002R0]:
8237  /// [...] the defaulted function itself is never a candidate for overload
8238  /// resolution [...]
8239  CandidateSet.exclude(FD);
8240 
8241  if (Args[0]->getType()->isOverloadableType())
8242  S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
8243  else
8244  // FIXME: We determine whether this is a valid expression by checking to
8245  // see if there's a viable builtin operator candidate for it. That isn't
8246  // really what the rules ask us to do, but should give the right results.
8247  S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
8248 
8249  Result R;
8250 
8252  switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
8253  case OR_Success: {
8254  // C++2a [class.compare.secondary]p2 [P2002R0]:
8255  // The operator function [...] is defined as deleted if [...] the
8256  // candidate selected by overload resolution is not a rewritten
8257  // candidate.
8258  if ((DCK == DefaultedComparisonKind::NotEqual ||
8260  !Best->RewriteKind) {
8261  if (Diagnose == ExplainDeleted) {
8262  if (Best->Function) {
8263  S.Diag(Best->Function->getLocation(),
8264  diag::note_defaulted_comparison_not_rewritten_callee)
8265  << FD;
8266  } else {
8267  assert(Best->Conversions.size() == 2 &&
8268  Best->Conversions[0].isUserDefined() &&
8269  "non-user-defined conversion from class to built-in "
8270  "comparison");
8271  S.Diag(Best->Conversions[0]
8272  .UserDefined.FoundConversionFunction.getDecl()
8273  ->getLocation(),
8274  diag::note_defaulted_comparison_not_rewritten_conversion)
8275  << FD;
8276  }
8277  }
8278  return Result::deleted();
8279  }
8280 
8281  // Throughout C++2a [class.compare]: if overload resolution does not
8282  // result in a usable function, the candidate function is defined as
8283  // deleted. This requires that we selected an accessible function.
8284  //
8285  // Note that this only considers the access of the function when named
8286  // within the type of the subobject, and not the access path for any
8287  // derived-to-base conversion.
8288  CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8289  if (ArgClass && Best->FoundDecl.getDecl() &&
8290  Best->FoundDecl.getDecl()->isCXXClassMember()) {
8291  QualType ObjectType = Subobj.Kind == Subobject::Member
8292  ? Args[0]->getType()
8293  : S.Context.getRecordType(RD);
8295  ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
8296  Diagnose == ExplainDeleted
8297  ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
8298  << FD << Subobj.Kind << Subobj.Decl
8299  : S.PDiag()))
8300  return Result::deleted();
8301  }
8302 
8303  bool NeedsDeducing =
8304  OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8305 
8306  if (FunctionDecl *BestFD = Best->Function) {
8307  // C++2a [class.compare.default]p3 [P2002R0]:
8308  // A defaulted comparison function is constexpr-compatible if
8309  // [...] no overlod resolution performed [...] results in a
8310  // non-constexpr function.
8311  assert(!BestFD->isDeleted() && "wrong overload resolution result");
8312  // If it's not constexpr, explain why not.
8313  if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8314  if (Subobj.Kind != Subobject::CompleteObject)
8315  S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8316  << Subobj.Kind << Subobj.Decl;
8317  S.Diag(BestFD->getLocation(),
8318  diag::note_defaulted_comparison_not_constexpr_here);
8319  // Bail out after explaining; we don't want any more notes.
8320  return Result::deleted();
8321  }
8322  R.Constexpr &= BestFD->isConstexpr();
8323 
8324  if (NeedsDeducing) {
8325  // If any callee has an undeduced return type, deduce it now.
8326  // FIXME: It's not clear how a failure here should be handled. For
8327  // now, we produce an eager diagnostic, because that is forward
8328  // compatible with most (all?) other reasonable options.
8329  if (BestFD->getReturnType()->isUndeducedType() &&
8330  S.DeduceReturnType(BestFD, FD->getLocation(),
8331  /*Diagnose=*/false)) {
8332  // Don't produce a duplicate error when asked to explain why the
8333  // comparison is deleted: we diagnosed that when initially checking
8334  // the defaulted operator.
8335  if (Diagnose == NoDiagnostics) {
8336  S.Diag(
8337  FD->getLocation(),
8338  diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8339  << Subobj.Kind << Subobj.Decl;
8340  S.Diag(
8341  Subobj.Loc,
8342  diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8343  << Subobj.Kind << Subobj.Decl;
8344  S.Diag(BestFD->getLocation(),
8345  diag::note_defaulted_comparison_cannot_deduce_callee)
8346  << Subobj.Kind << Subobj.Decl;
8347  }
8348  return Result::deleted();
8349  }
8350  auto *Info = S.Context.CompCategories.lookupInfoForType(
8351  BestFD->getCallResultType());
8352  if (!Info) {
8353  if (Diagnose == ExplainDeleted) {
8354  S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8355  << Subobj.Kind << Subobj.Decl
8356  << BestFD->getCallResultType().withoutLocalFastQualifiers();
8357  S.Diag(BestFD->getLocation(),
8358  diag::note_defaulted_comparison_cannot_deduce_callee)
8359  << Subobj.Kind << Subobj.Decl;
8360  }
8361  return Result::deleted();
8362  }
8363  R.Category = Info->Kind;
8364  }
8365  } else {
8366  QualType T = Best->BuiltinParamTypes[0];
8367  assert(T == Best->BuiltinParamTypes[1] &&
8368  "builtin comparison for different types?");
8369  assert(Best->BuiltinParamTypes[2].isNull() &&
8370  "invalid builtin comparison");
8371 
8372  if (NeedsDeducing) {
8373  std::optional<ComparisonCategoryType> Cat =
8375  assert(Cat && "no category for builtin comparison?");
8376  R.Category = *Cat;
8377  }
8378  }
8379 
8380  // Note that we might be rewriting to a different operator. That call is
8381  // not considered until we come to actually build the comparison function.
8382  break;
8383  }
8384 
8385  case OR_Ambiguous:
8386  if (Diagnose == ExplainDeleted) {
8387  unsigned Kind = 0;
8388  if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8389  Kind = OO == OO_EqualEqual ? 1 : 2;
8390  CandidateSet.NoteCandidates(
8392  Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8393  << FD << Kind << Subobj.Kind << Subobj.Decl),
8394  S, OCD_AmbiguousCandidates, Args);
8395  }
8396  R = Result::deleted();
8397  break;
8398 
8399  case OR_Deleted:
8400  if (Diagnose == ExplainDeleted) {
8401  if ((DCK == DefaultedComparisonKind::NotEqual ||
8403  !Best->RewriteKind) {
8404  S.Diag(Best->Function->getLocation(),
8405  diag::note_defaulted_comparison_not_rewritten_callee)
8406  << FD;
8407  } else {
8408  S.Diag(Subobj.Loc,
8409  diag::note_defaulted_comparison_calls_deleted)
8410  << FD << Subobj.Kind << Subobj.Decl;
8411  S.NoteDeletedFunction(Best->Function);
8412  }
8413  }
8414  R = Result::deleted();
8415  break;
8416 
8417  case OR_No_Viable_Function:
8418  // If there's no usable candidate, we're done unless we can rewrite a
8419  // '<=>' in terms of '==' and '<'.
8420  if (OO == OO_Spaceship &&
8422  // For any kind of comparison category return type, we need a usable
8423  // '==' and a usable '<'.
8424  if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8425  &CandidateSet)))
8426  R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8427  break;
8428  }
8429 
8430  if (Diagnose == ExplainDeleted) {
8431  S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8432  << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8433  << Subobj.Kind << Subobj.Decl;
8434 
8435  // For a three-way comparison, list both the candidates for the
8436  // original operator and the candidates for the synthesized operator.
8437  if (SpaceshipCandidates) {
8438  SpaceshipCandidates->NoteCandidates(
8439  S, Args,
8440  SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8441  Args, FD->getLocation()));
8442  S.Diag(Subobj.Loc,
8443  diag::note_defaulted_comparison_no_viable_function_synthesized)
8444  << (OO == OO_EqualEqual ? 0 : 1);
8445  }
8446 
8447  CandidateSet.NoteCandidates(
8448  S, Args,
8449  CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8450  FD->getLocation()));
8451  }
8452  R = Result::deleted();
8453  break;
8454  }
8455 
8456  return R;
8457  }
8458 };
8459 
8460 /// A list of statements.
8461 struct StmtListResult {
8462  bool IsInvalid = false;
8464 
8465  bool add(const StmtResult &S) {
8466  IsInvalid |= S.isInvalid();
8467  if (IsInvalid)
8468  return true;
8469  Stmts.push_back(S.get());
8470  return false;
8471  }
8472 };
8473 
8474 /// A visitor over the notional body of a defaulted comparison that synthesizes
8475 /// the actual body.
8476 class DefaultedComparisonSynthesizer
8477  : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8478  StmtListResult, StmtResult,
8479  std::pair<ExprResult, ExprResult>> {
8480  SourceLocation Loc;
8481  unsigned ArrayDepth = 0;
8482 
8483 public:
8484  using Base = DefaultedComparisonVisitor;
8485  using ExprPair = std::pair<ExprResult, ExprResult>;
8486 
8487  friend Base;
8488 
8489  DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8491  SourceLocation BodyLoc)
8492  : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8493 
8494  /// Build a suitable function body for this defaulted comparison operator.
8495  StmtResult build() {
8496  Sema::CompoundScopeRAII CompoundScope(S);
8497 
8498  StmtListResult Stmts = visit();
8499  if (Stmts.IsInvalid)
8500  return StmtError();
8501 
8502  ExprResult RetVal;
8503  switch (DCK) {
8505  llvm_unreachable("not a defaulted comparison");
8506 
8508  // C++2a [class.eq]p3:
8509  // [...] compar[e] the corresponding elements [...] until the first
8510  // index i where xi == yi yields [...] false. If no such index exists,
8511  // V is true. Otherwise, V is false.
8512  //
8513  // Join the comparisons with '&&'s and return the result. Use a right
8514  // fold (traversing the conditions right-to-left), because that
8515  // short-circuits more naturally.
8516  auto OldStmts = std::move(Stmts.Stmts);
8517  Stmts.Stmts.clear();
8518  ExprResult CmpSoFar;
8519  // Finish a particular comparison chain.
8520  auto FinishCmp = [&] {
8521  if (Expr *Prior = CmpSoFar.get()) {
8522  // Convert the last expression to 'return ...;'
8523  if (RetVal.isUnset() && Stmts.Stmts.empty())
8524  RetVal = CmpSoFar;
8525  // Convert any prior comparison to 'if (!(...)) return false;'
8526  else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8527  return true;
8528  CmpSoFar = ExprResult();
8529  }
8530  return false;
8531  };
8532  for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8533  Expr *E = dyn_cast<Expr>(EAsStmt);
8534  if (!E) {
8535  // Found an array comparison.
8536  if (FinishCmp() || Stmts.add(EAsStmt))
8537  return StmtError();
8538  continue;
8539  }
8540 
8541  if (CmpSoFar.isUnset()) {
8542  CmpSoFar = E;
8543  continue;
8544  }
8545  CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8546  if (CmpSoFar.isInvalid())
8547  return StmtError();
8548  }
8549  if (FinishCmp())
8550  return StmtError();
8551  std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8552  // If no such index exists, V is true.
8553  if (RetVal.isUnset())
8554  RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8555  break;
8556  }
8557 
8559  // Per C++2a [class.spaceship]p3, as a fallback add:
8560  // return static_cast<R>(std::strong_ordering::equal);
8564  if (StrongOrdering.isNull())
8565  return StmtError();
8566  VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8568  ->VD;
8569  RetVal = getDecl(EqualVD);
8570  if (RetVal.isInvalid())
8571  return StmtError();
8572  RetVal = buildStaticCastToR(RetVal.get());
8573  break;
8574  }
8575 
8578  RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8579  break;
8580  }
8581 
8582  // Build the final return statement.
8583  if (RetVal.isInvalid())
8584  return StmtError();
8585  StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8586  if (ReturnStmt.isInvalid())
8587  return StmtError();
8588  Stmts.Stmts.push_back(ReturnStmt.get());
8589 
8590  return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8591  }
8592 
8593 private:
8594  ExprResult getDecl(ValueDecl *VD) {
8595  return S.BuildDeclarationNameExpr(
8596  CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8597  }
8598 
8599  ExprResult getParam(unsigned I) {
8600  ParmVarDecl *PD = FD->getParamDecl(I);
8601  return getDecl(PD);
8602  }
8603 
8604  ExprPair getCompleteObject() {
8605  unsigned Param = 0;
8606  ExprResult LHS;
8607  if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
8608  MD && MD->isImplicitObjectMemberFunction()) {
8609  // LHS is '*this'.
8610  LHS = S.ActOnCXXThis(Loc);
8611  if (!LHS.isInvalid())
8612  LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8613  } else {
8614  LHS = getParam(Param++);
8615  }
8616  ExprResult RHS = getParam(Param++);
8617  assert(Param == FD->getNumParams());
8618  return {LHS, RHS};
8619  }
8620 
8621  ExprPair getBase(CXXBaseSpecifier *Base) {
8622  ExprPair Obj = getCompleteObject();
8623  if (Obj.first.isInvalid() || Obj.second.isInvalid())
8624  return {ExprError(), ExprError()};
8625  CXXCastPath Path = {Base};
8626  return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8627  CK_DerivedToBase, VK_LValue, &Path),
8628  S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8629  CK_DerivedToBase, VK_LValue, &Path)};
8630  }
8631 
8632  ExprPair getField(FieldDecl *Field) {
8633  ExprPair Obj = getCompleteObject();
8634  if (Obj.first.isInvalid() || Obj.second.isInvalid())
8635  return {ExprError(), ExprError()};
8636 
8637  DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8638  DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8639  return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8640  CXXScopeSpec(), Field, Found, NameInfo),
8641  S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8642  CXXScopeSpec(), Field, Found, NameInfo)};
8643  }
8644 
8645  // FIXME: When expanding a subobject, register a note in the code synthesis
8646  // stack to say which subobject we're comparing.
8647 
8648  StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8649  if (Cond.isInvalid())
8650  return StmtError();
8651 
8652  ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8653  if (NotCond.isInvalid())
8654  return StmtError();
8655 
8656  ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8657  assert(!False.isInvalid() && "should never fail");
8658  StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8659  if (ReturnFalse.isInvalid())
8660  return StmtError();
8661 
8662  return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8663  S.ActOnCondition(nullptr, Loc, NotCond.get(),
8665  Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8666  }
8667 
8668  StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8669  ExprPair Subobj) {
8670  QualType SizeType = S.Context.getSizeType();
8671  Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8672 
8673  // Build 'size_t i$n = 0'.
8674  IdentifierInfo *IterationVarName = nullptr;
8675  {
8676  SmallString<8> Str;
8677  llvm::raw_svector_ostream OS(Str);
8678  OS << "i" << ArrayDepth;
8679  IterationVarName = &S.Context.Idents.get(OS.str());
8680  }
8681  VarDecl *IterationVar = VarDecl::Create(
8682  S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8683  S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8684  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8685  IterationVar->setInit(
8686  IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8687  Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8688 
8689  auto IterRef = [&] {
8691  CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8692  IterationVar);
8693  assert(!Ref.isInvalid() && "can't reference our own variable?");
8694  return Ref.get();
8695  };
8696 
8697  // Build 'i$n != Size'.
8698  ExprResult Cond = S.CreateBuiltinBinOp(
8699  Loc, BO_NE, IterRef(),
8700  IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8701  assert(!Cond.isInvalid() && "should never fail");
8702 
8703  // Build '++i$n'.
8704  ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8705  assert(!Inc.isInvalid() && "should never fail");
8706 
8707  // Build 'a[i$n]' and 'b[i$n]'.
8708  auto Index = [&](ExprResult E) {
8709  if (E.isInvalid())
8710  return ExprError();
8711  return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8712  };
8713  Subobj.first = Index(Subobj.first);
8714  Subobj.second = Index(Subobj.second);
8715 
8716  // Compare the array elements.
8717  ++ArrayDepth;
8718  StmtResult Substmt = visitSubobject(Type, Subobj);
8719  --ArrayDepth;
8720 
8721  if (Substmt.isInvalid())
8722  return StmtError();
8723 
8724  // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8725  // For outer levels or for an 'operator<=>' we already have a suitable
8726  // statement that returns as necessary.
8727  if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8728  assert(DCK == DefaultedComparisonKind::Equal &&
8729  "should have non-expression statement");
8730  Substmt = buildIfNotCondReturnFalse(ElemCmp);
8731  if (Substmt.isInvalid())
8732  return StmtError();
8733  }
8734 
8735  // Build 'for (...) ...'
8736  return S.ActOnForStmt(Loc, Loc, Init,
8737  S.ActOnCondition(nullptr, Loc, Cond.get(),
8739  S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8740  Substmt.get());
8741  }
8742 
8743  StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8744  if (Obj.first.isInvalid() || Obj.second.isInvalid())
8745  return StmtError();
8746 
8749  ExprResult Op;
8750  if (Type->isOverloadableType())
8751  Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8752  Obj.second.get(), /*PerformADL=*/true,
8753  /*AllowRewrittenCandidates=*/true, FD);
8754  else
8755  Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8756  if (Op.isInvalid())
8757  return StmtError();
8758 
8759  switch (DCK) {
8761  llvm_unreachable("not a defaulted comparison");
8762 
8764  // Per C++2a [class.eq]p2, each comparison is individually contextually
8765  // converted to bool.
8767  if (Op.isInvalid())
8768  return StmtError();
8769  return Op.get();
8770 
8772  // Per C++2a [class.spaceship]p3, form:
8773  // if (R cmp = static_cast<R>(op); cmp != 0)
8774  // return cmp;
8775  QualType R = FD->getReturnType();
8776  Op = buildStaticCastToR(Op.get());
8777  if (Op.isInvalid())
8778  return StmtError();
8779 
8780  // R cmp = ...;
8781  IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8782  VarDecl *VD =
8783  VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8785  S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8786  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8787 
8788  // cmp != 0
8789  ExprResult VDRef = getDecl(VD);
8790  if (VDRef.isInvalid())
8791  return StmtError();
8792  llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8793  Expr *Zero =
8794  IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8795  ExprResult Comp;
8796  if (VDRef.get()->getType()->isOverloadableType())
8797  Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8798  true, FD);
8799  else
8800  Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8801  if (Comp.isInvalid())
8802  return StmtError();
8804  nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8805  if (Cond.isInvalid())
8806  return StmtError();
8807 
8808  // return cmp;
8809  VDRef = getDecl(VD);
8810  if (VDRef.isInvalid())
8811  return StmtError();
8812  StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8813  if (ReturnStmt.isInvalid())
8814  return StmtError();
8815 
8816  // if (...)
8817  return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8818  Loc, ReturnStmt.get(),
8819  /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8820  }
8821 
8824  // C++2a [class.compare.secondary]p2:
8825  // Otherwise, the operator function yields x @ y.
8826  return Op.get();
8827  }
8828  llvm_unreachable("");
8829  }
8830 
8831  /// Build "static_cast<R>(E)".
8832  ExprResult buildStaticCastToR(Expr *E) {
8833  QualType R = FD->getReturnType();
8834  assert(!R->isUndeducedType() && "type should have been deduced already");
8835 
8836  // Don't bother forming a no-op cast in the common case.
8837  if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8838  return E;
8839  return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8840  S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8841  SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8842  }
8843 };
8844 }
8845 
8846 /// Perform the unqualified lookups that might be needed to form a defaulted
8847 /// comparison function for the given operator.
8849  UnresolvedSetImpl &Operators,
8851  auto Lookup = [&](OverloadedOperatorKind OO) {
8852  Self.LookupOverloadedOperatorName(OO, S, Operators);
8853  };
8854 
8855  // Every defaulted operator looks up itself.
8856  Lookup(Op);
8857  // ... and the rewritten form of itself, if any.
8859  Lookup(ExtraOp);
8860 
8861  // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8862  // synthesize a three-way comparison from '<' and '=='. In a dependent
8863  // context, we also need to look up '==' in case we implicitly declare a
8864  // defaulted 'operator=='.
8865  if (Op == OO_Spaceship) {
8866  Lookup(OO_ExclaimEqual);
8867  Lookup(OO_Less);
8868  Lookup(OO_EqualEqual);
8869  }
8870 }
8871 
8874  assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8875 
8876  // Perform any unqualified lookups we're going to need to default this
8877  // function.
8878  if (S) {
8879  UnresolvedSet<32> Operators;
8880  lookupOperatorsForDefaultedComparison(*this, S, Operators,
8881  FD->getOverloadedOperator());
8884  Context, Operators.pairs()));
8885  }
8886 
8887  // C++2a [class.compare.default]p1:
8888  // A defaulted comparison operator function for some class C shall be a
8889  // non-template function declared in the member-specification of C that is
8890  // -- a non-static const non-volatile member of C having one parameter of
8891  // type const C& and either no ref-qualifier or the ref-qualifier &, or
8892  // -- a friend of C having two parameters of type const C& or two
8893  // parameters of type C.
8894 
8895  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8896  bool IsMethod = isa<CXXMethodDecl>(FD);
8897  if (IsMethod) {
8898  auto *MD = cast<CXXMethodDecl>(FD);
8899  assert(!MD->isStatic() && "comparison function cannot be a static member");
8900 
8901  if (MD->getRefQualifier() == RQ_RValue) {
8902  Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator);
8903 
8904  // Remove the ref qualifier to recover.
8905  const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8906  FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8907  EPI.RefQualifier = RQ_None;
8908  MD->setType(Context.getFunctionType(FPT->getReturnType(),
8909  FPT->getParamTypes(), EPI));
8910  }
8911 
8912  // If we're out-of-class, this is the class we're comparing.
8913  if (!RD)
8914  RD = MD->getParent();
8916  if (!T.isConstQualified()) {
8917  SourceLocation Loc, InsertLoc;
8918  if (MD->isExplicitObjectMemberFunction()) {
8919  Loc = MD->getParamDecl(0)->getBeginLoc();
8920  InsertLoc = getLocForEndOfToken(
8922  } else {
8923  Loc = MD->getLocation();
8924  if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8925  InsertLoc = Loc.getRParenLoc();
8926  }
8927  // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8928  // corresponding defaulted 'operator<=>' already.
8929  if (!MD->isImplicit()) {
8930  Diag(Loc, diag::err_defaulted_comparison_non_const)
8931  << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8932  }
8933 
8934  // Add the 'const' to the type to recover.
8935  const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8936  FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8937  EPI.TypeQuals.addConst();
8938  MD->setType(Context.getFunctionType(FPT->getReturnType(),
8939  FPT->getParamTypes(), EPI));
8940  }
8941 
8942  if (MD->isVolatile()) {
8943  Diag(MD->getLocation(), diag::err_volatile_comparison_operator);
8944 
8945  // Remove the 'volatile' from the type to recover.
8946  const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8947  FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8948  EPI.TypeQuals.removeVolatile();
8949  MD->setType(Context.getFunctionType(FPT->getReturnType(),
8950  FPT->getParamTypes(), EPI));
8951  }
8952  }
8953 
8954  if ((FD->getNumParams() -
8955  (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
8956  (IsMethod ? 1 : 2)) {
8957  // Let's not worry about using a variadic template pack here -- who would do
8958  // such a thing?
8959  Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
8960  << int(IsMethod) << int(DCK);
8961  return true;
8962  }
8963 
8964  const ParmVarDecl *KnownParm = nullptr;
8965  for (const ParmVarDecl *Param : FD->parameters()) {
8966  if (Param->isExplicitObjectParameter())
8967  continue;
8968  QualType ParmTy = Param->getType();
8969 
8970  if (!KnownParm) {
8971  auto CTy = ParmTy;
8972  // Is it `T const &`?
8973  bool Ok = !IsMethod;
8974  QualType ExpectedTy;
8975  if (RD)
8976  ExpectedTy = Context.getRecordType(RD);
8977  if (auto *Ref = CTy->getAs<ReferenceType>()) {
8978  CTy = Ref->getPointeeType();
8979  if (RD)
8980  ExpectedTy.addConst();
8981  Ok = true;
8982  }
8983 
8984  // Is T a class?
8985  if (!Ok) {
8986  } else if (RD) {
8987  if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy))
8988  Ok = false;
8989  } else if (auto *CRD = CTy->getAsRecordDecl()) {
8990  RD = cast<CXXRecordDecl>(CRD);
8991  } else {
8992  Ok = false;
8993  }
8994 
8995  if (Ok) {
8996  KnownParm = Param;
8997  } else {
8998  // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8999  // corresponding defaulted 'operator<=>' already.
9000  if (!FD->isImplicit()) {
9001  if (RD) {
9002  QualType PlainTy = Context.getRecordType(RD);
9003  QualType RefTy =
9005  Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
9006  << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
9007  << Param->getSourceRange();
9008  } else {
9009  assert(!IsMethod && "should know expected type for method");
9010  Diag(FD->getLocation(),
9011  diag::err_defaulted_comparison_param_unknown)
9012  << int(DCK) << ParmTy << Param->getSourceRange();
9013  }
9014  }
9015  return true;
9016  }
9017  } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
9018  Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
9019  << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
9020  << ParmTy << Param->getSourceRange();
9021  return true;
9022  }
9023  }
9024 
9025  assert(RD && "must have determined class");
9026  if (IsMethod) {
9027  } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
9028  // In-class, must be a friend decl.
9029  assert(FD->getFriendObjectKind() && "expected a friend declaration");
9030  } else {
9031  // Out of class, require the defaulted comparison to be a friend (of a
9032  // complete type).
9034  diag::err_defaulted_comparison_not_friend, int(DCK),
9035  int(1)))
9036  return true;
9037 
9038  if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
9039  return FD->getCanonicalDecl() ==
9040  F->getFriendDecl()->getCanonicalDecl();
9041  })) {
9042  Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
9043  << int(DCK) << int(0) << RD;
9044  Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
9045  return true;
9046  }
9047  }
9048 
9049  // C++2a [class.eq]p1, [class.rel]p1:
9050  // A [defaulted comparison other than <=>] shall have a declared return
9051  // type bool.
9052  if (DCK != DefaultedComparisonKind::ThreeWay &&
9055  Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
9056  << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
9057  << FD->getReturnTypeSourceRange();
9058  return true;
9059  }
9060  // C++2a [class.spaceship]p2 [P2002R0]:
9061  // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
9062  // R shall not contain a placeholder type.
9063  if (QualType RT = FD->getDeclaredReturnType();
9065  RT->getContainedDeducedType() &&
9067  RT->getContainedAutoType()->isConstrained())) {
9068  Diag(FD->getLocation(),
9069  diag::err_defaulted_comparison_deduced_return_type_not_auto)
9070  << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
9071  << FD->getReturnTypeSourceRange();
9072  return true;
9073  }
9074 
9075  // For a defaulted function in a dependent class, defer all remaining checks
9076  // until instantiation.
9077  if (RD->isDependentType())
9078  return false;
9079 
9080  // Determine whether the function should be defined as deleted.
9081  DefaultedComparisonInfo Info =
9082  DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
9083 
9084  bool First = FD == FD->getCanonicalDecl();
9085 
9086  if (!First) {
9087  if (Info.Deleted) {
9088  // C++11 [dcl.fct.def.default]p4:
9089  // [For a] user-provided explicitly-defaulted function [...] if such a
9090  // function is implicitly defined as deleted, the program is ill-formed.
9091  //
9092  // This is really just a consequence of the general rule that you can
9093  // only delete a function on its first declaration.
9094  Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
9095  << FD->isImplicit() << (int)DCK;
9096  DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9097  DefaultedComparisonAnalyzer::ExplainDeleted)
9098  .visit();
9099  return true;
9100  }
9101  if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
9102  // C++20 [class.compare.default]p1:
9103  // [...] A definition of a comparison operator as defaulted that appears
9104  // in a class shall be the first declaration of that function.
9105  Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)
9106  << (int)DCK;
9108  diag::note_previous_declaration);
9109  return true;
9110  }
9111  }
9112 
9113  // If we want to delete the function, then do so; there's nothing else to
9114  // check in that case.
9115  if (Info.Deleted) {
9116  SetDeclDeleted(FD, FD->getLocation());
9117  if (!inTemplateInstantiation() && !FD->isImplicit()) {
9118  Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
9119  << (int)DCK;
9120  DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9121  DefaultedComparisonAnalyzer::ExplainDeleted)
9122  .visit();
9123  if (FD->getDefaultLoc().isValid())
9124  Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
9125  << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
9126  }
9127  return false;
9128  }
9129 
9130  // C++2a [class.spaceship]p2:
9131  // The return type is deduced as the common comparison type of R0, R1, ...
9132  if (DCK == DefaultedComparisonKind::ThreeWay &&
9135  if (RetLoc.isInvalid())
9136  RetLoc = FD->getBeginLoc();
9137  // FIXME: Should we really care whether we have the complete type and the
9138  // 'enumerator' constants here? A forward declaration seems sufficient.
9140  Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
9141  if (Cat.isNull())
9142  return true;
9144  FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
9145  }
9146 
9147  // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9148  // An explicitly-defaulted function that is not defined as deleted may be
9149  // declared constexpr or consteval only if it is constexpr-compatible.
9150  // C++2a [class.compare.default]p3 [P2002R0]:
9151  // A defaulted comparison function is constexpr-compatible if it satisfies
9152  // the requirements for a constexpr function [...]
9153  // The only relevant requirements are that the parameter and return types are
9154  // literal types. The remaining conditions are checked by the analyzer.
9155  //
9156  // We support P2448R2 in language modes earlier than C++23 as an extension.
9157  // The concept of constexpr-compatible was removed.
9158  // C++23 [dcl.fct.def.default]p3 [P2448R2]
9159  // A function explicitly defaulted on its first declaration is implicitly
9160  // inline, and is implicitly constexpr if it is constexpr-suitable.
9161  // C++23 [dcl.constexpr]p3
9162  // A function is constexpr-suitable if
9163  // - it is not a coroutine, and
9164  // - if the function is a constructor or destructor, its class does not
9165  // have any virtual base classes.
9166  if (FD->isConstexpr()) {
9167  if (!getLangOpts().CPlusPlus23 &&
9170  !Info.Constexpr) {
9171  Diag(FD->getBeginLoc(), diag::err_defaulted_comparison_constexpr_mismatch)
9172  << FD->isImplicit() << (int)DCK << FD->isConsteval();
9173  DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9174  DefaultedComparisonAnalyzer::ExplainConstexpr)
9175  .visit();
9176  }
9177  }
9178 
9179  // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9180  // If a constexpr-compatible function is explicitly defaulted on its first
9181  // declaration, it is implicitly considered to be constexpr.
9182  // FIXME: Only applying this to the first declaration seems problematic, as
9183  // simple reorderings can affect the meaning of the program.
9184  if (First && !FD->isConstexpr() && Info.Constexpr)
9186 
9187  // C++2a [except.spec]p3:
9188  // If a declaration of a function does not have a noexcept-specifier
9189  // [and] is defaulted on its first declaration, [...] the exception
9190  // specification is as specified below
9191  if (FD->getExceptionSpecType() == EST_None) {
9192  auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9193  FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9195  EPI.ExceptionSpec.SourceDecl = FD;
9196  FD->setType(Context.getFunctionType(FPT->getReturnType(),
9197  FPT->getParamTypes(), EPI));
9198  }
9199 
9200  return false;
9201 }
9202 
9207  Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9208  Ctx.Entity = Spaceship;
9210 
9211  if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9212  EqualEqual->setImplicit();
9213 
9215 }
9216 
9219  assert(FD->isDefaulted() && !FD->isDeleted() &&
9221  if (FD->willHaveBody() || FD->isInvalidDecl())
9222  return;
9223 
9224  SynthesizedFunctionScope Scope(*this, FD);
9225 
9226  // Add a context note for diagnostics produced after this point.
9227  Scope.addContextNote(UseLoc);
9228 
9229  {
9230  // Build and set up the function body.
9231  // The first parameter has type maybe-ref-to maybe-const T, use that to get
9232  // the type of the class being compared.
9233  auto PT = FD->getParamDecl(0)->getType();
9234  CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9235  SourceLocation BodyLoc =
9236  FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9237  StmtResult Body =
9238  DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9239  if (Body.isInvalid()) {
9240  FD->setInvalidDecl();
9241  return;
9242  }
9243  FD->setBody(Body.get());
9244  FD->markUsed(Context);
9245  }
9246 
9247  // The exception specification is needed because we are defining the
9248  // function. Note that this will reuse the body we just built.
9250 
9252  L->CompletedImplicitDefinition(FD);
9253 }
9254 
9257  FunctionDecl *FD,
9259  ComputingExceptionSpec CES(S, FD, Loc);
9261 
9262  if (FD->isInvalidDecl())
9263  return ExceptSpec;
9264 
9265  // The common case is that we just defined the comparison function. In that
9266  // case, just look at whether the body can throw.
9267  if (FD->hasBody()) {
9268  ExceptSpec.CalledStmt(FD->getBody());
9269  } else {
9270  // Otherwise, build a body so we can check it. This should ideally only
9271  // happen when we're not actually marking the function referenced. (This is
9272  // only really important for efficiency: we don't want to build and throw
9273  // away bodies for comparison functions more than we strictly need to.)
9274 
9275  // Pretend to synthesize the function body in an unevaluated context.
9276  // Note that we can't actually just go ahead and define the function here:
9277  // we are not permitted to mark its callees as referenced.
9281 
9282  CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
9283  SourceLocation BodyLoc =
9284  FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9285  StmtResult Body =
9286  DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9287  if (!Body.isInvalid())
9288  ExceptSpec.CalledStmt(Body.get());
9289 
9290  // FIXME: Can we hold onto this body and just transform it to potentially
9291  // evaluated when we're asked to define the function rather than rebuilding
9292  // it? Either that, or we should only build the bits of the body that we
9293  // need (the expressions, not the statements).
9294  }
9295 
9296  return ExceptSpec;
9297 }
9298 
9300  decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9302 
9303  std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
9305 
9306  // Perform any deferred checking of exception specifications for virtual
9307  // destructors.
9308  for (auto &Check : Overriding)
9309  CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
9310 
9311  // Perform any deferred checking of exception specifications for befriended
9312  // special members.
9313  for (auto &Check : Equivalent)
9314  CheckEquivalentExceptionSpec(Check.second, Check.first);
9315 }
9316 
9317 namespace {
9318 /// CRTP base class for visiting operations performed by a special member
9319 /// function (or inherited constructor).
9320 template<typename Derived>
9321 struct SpecialMemberVisitor {
9322  Sema &S;
9323  CXXMethodDecl *MD;
9326 
9327  // Properties of the special member, computed for convenience.
9328  bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9329 
9330  SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
9332  : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9333  switch (CSM) {
9337  IsConstructor = true;
9338  break;
9341  IsAssignment = true;
9342  break;
9344  break;
9346  llvm_unreachable("invalid special member kind");
9347  }
9348 
9349  if (MD->getNumExplicitParams()) {
9350  if (const ReferenceType *RT =
9352  ConstArg = RT->getPointeeType().isConstQualified();
9353  }
9354  }
9355 
9356  Derived &getDerived() { return static_cast<Derived&>(*this); }
9357 
9358  /// Is this a "move" special member?
9359  bool isMove() const {
9360  return CSM == CXXSpecialMemberKind::MoveConstructor ||
9362  }
9363 
9364  /// Look up the corresponding special member in the given class.
9366  unsigned Quals, bool IsMutable) {
9367  return lookupCallFromSpecialMember(S, Class, CSM, Quals,
9368  ConstArg && !IsMutable);
9369  }
9370 
9371  /// Look up the constructor for the specified base class to see if it's
9372  /// overridden due to this being an inherited constructor.
9373  Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9374  if (!ICI)
9375  return {};
9377  auto *BaseCtor =
9378  cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
9379  if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
9380  return MD;
9381  return {};
9382  }
9383 
9384  /// A base or member subobject.
9385  typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9386 
9387  /// Get the location to use for a subobject in diagnostics.
9388  static SourceLocation getSubobjectLoc(Subobject Subobj) {
9389  // FIXME: For an indirect virtual base, the direct base leading to
9390  // the indirect virtual base would be a more useful choice.
9391  if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
9392  return B->getBaseTypeLoc();
9393  else
9394  return Subobj.get<FieldDecl*>()->getLocation();
9395  }
9396 
9397  enum BasesToVisit {
9398  /// Visit all non-virtual (direct) bases.
9399  VisitNonVirtualBases,
9400  /// Visit all direct bases, virtual or not.
9401  VisitDirectBases,
9402  /// Visit all non-virtual bases, and all virtual bases if the class
9403  /// is not abstract.
9404  VisitPotentiallyConstructedBases,
9405  /// Visit all direct or virtual bases.
9406  VisitAllBases
9407  };
9408 
9409  // Visit the bases and members of the class.
9410  bool visit(BasesToVisit Bases) {
9411  CXXRecordDecl *RD = MD->getParent();
9412 
9413  if (Bases == VisitPotentiallyConstructedBases)
9414  Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9415 
9416  for (auto &B : RD->bases())
9417  if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9418  getDerived().visitBase(&B))
9419  return true;
9420 
9421  if (Bases == VisitAllBases)
9422  for (auto &B : RD->vbases())
9423  if (getDerived().visitBase(&B))
9424  return true;
9425 
9426  for (auto *F : RD->fields())
9427  if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
9428  getDerived().visitField(F))
9429  return true;
9430 
9431  return false;
9432  }
9433 };
9434 }
9435 
9436 namespace {
9437 struct SpecialMemberDeletionInfo
9438  : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9439  bool Diagnose;
9440 
9441  SourceLocation Loc;
9442 
9443  bool AllFieldsAreConst;
9444 
9445  SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9447  Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9448  : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9449  Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9450 
9451  bool inUnion() const { return MD->getParent()->isUnion(); }
9452 
9453  CXXSpecialMemberKind getEffectiveCSM() {
9454  return ICI ? CXXSpecialMemberKind::Invalid : CSM;
9455  }
9456 
9457  bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9458 
9459  bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9460  bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9461 
9462  bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9463  bool shouldDeleteForField(FieldDecl *FD);
9464  bool shouldDeleteForAllConstMembers();
9465 
9466  bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9467  unsigned Quals);
9468  bool shouldDeleteForSubobjectCall(Subobject Subobj,
9470  bool IsDtorCallInCtor);
9471 
9472  bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9473 };
9474 }
9475 
9476 /// Is the given special member inaccessible when used on the given
9477 /// sub-object.
9478 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9479  CXXMethodDecl *target) {
9480  /// If we're operating on a base class, the object type is the
9481  /// type of this special member.
9482  QualType objectTy;
9483  AccessSpecifier access = target->getAccess();
9484  if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9485  objectTy = S.Context.getTypeDeclType(MD->getParent());
9486  access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9487 
9488  // If we're operating on a field, the object type is the type of the field.
9489  } else {
9490  objectTy = S.Context.getTypeDeclType(target->getParent());
9491  }
9492 
9494  target->getParent(), DeclAccessPair::make(target, access), objectTy);
9495 }
9496 
9497 /// Check whether we should delete a special member due to the implicit
9498 /// definition containing a call to a special member of a subobject.
9499 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9500  Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9501  bool IsDtorCallInCtor) {
9502  CXXMethodDecl *Decl = SMOR.getMethod();
9503  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9504 
9505  int DiagKind = -1;
9506 
9508  DiagKind = !Decl ? 0 : 1;
9510  DiagKind = 2;
9511  else if (!isAccessible(Subobj, Decl))
9512  DiagKind = 3;
9513  else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9514  !Decl->isTrivial()) {
9515  // A member of a union must have a trivial corresponding special member.
9516  // As a weird special case, a destructor call from a union's constructor
9517  // must be accessible and non-deleted, but need not be trivial. Such a
9518  // destructor is never actually called, but is semantically checked as
9519  // if it were.
9521  // [class.default.ctor]p2:
9522  // A defaulted default constructor for class X is defined as deleted if
9523  // - X is a union that has a variant member with a non-trivial default
9524  // constructor and no variant member of X has a default member
9525  // initializer
9526  const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9527  if (!RD->hasInClassInitializer())
9528  DiagKind = 4;
9529  } else {
9530  DiagKind = 4;
9531  }
9532  }
9533 
9534  if (DiagKind == -1)
9535  return false;
9536 
9537  if (Diagnose) {
9538  if (Field) {
9539  S.Diag(Field->getLocation(),
9540  diag::note_deleted_special_member_class_subobject)
9541  << llvm::to_underlying(getEffectiveCSM()) << MD->getParent()
9542  << /*IsField*/ true << Field << DiagKind << IsDtorCallInCtor
9543  << /*IsObjCPtr*/ false;
9544  } else {
9545  CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
9546  S.Diag(Base->getBeginLoc(),
9547  diag::note_deleted_special_member_class_subobject)
9548  << llvm::to_underlying(getEffectiveCSM()) << MD->getParent()
9549  << /*IsField*/ false << Base->getType() << DiagKind
9550  << IsDtorCallInCtor << /*IsObjCPtr*/ false;
9551  }
9552 
9553  if (DiagKind == 1)
9555  // FIXME: Explain inaccessibility if DiagKind == 3.
9556  }
9557 
9558  return true;
9559 }
9560 
9561 /// Check whether we should delete a special member function due to having a
9562 /// direct or virtual base class or non-static data member of class type M.
9563 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9564  CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9565  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9566  bool IsMutable = Field && Field->isMutable();
9567 
9568  // C++11 [class.ctor]p5:
9569  // -- any direct or virtual base class, or non-static data member with no
9570  // brace-or-equal-initializer, has class type M (or array thereof) and
9571  // either M has no default constructor or overload resolution as applied
9572  // to M's default constructor results in an ambiguity or in a function
9573  // that is deleted or inaccessible
9574  // C++11 [class.copy]p11, C++11 [class.copy]p23:
9575  // -- a direct or virtual base class B that cannot be copied/moved because
9576  // overload resolution, as applied to B's corresponding special member,
9577  // results in an ambiguity or a function that is deleted or inaccessible
9578  // from the defaulted special member
9579  // C++11 [class.dtor]p5:
9580  // -- any direct or virtual base class [...] has a type with a destructor
9581  // that is deleted or inaccessible
9582  if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9583  Field->hasInClassInitializer()) &&
9584  shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9585  false))
9586  return true;
9587 
9588  // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9589  // -- any direct or virtual base class or non-static data member has a
9590  // type with a destructor that is deleted or inaccessible
9591  if (IsConstructor) {
9594  false, false, false, false);
9595  if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9596  return true;
9597  }
9598 
9599  return false;
9600 }
9601 
9602 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9603  FieldDecl *FD, QualType FieldType) {
9604  // The defaulted special functions are defined as deleted if this is a variant
9605  // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9606  // type under ARC.
9607  if (!FieldType.hasNonTrivialObjCLifetime())
9608  return false;
9609 
9610  // Don't make the defaulted default constructor defined as deleted if the
9611  // member has an in-class initializer.
9613  FD->hasInClassInitializer())
9614  return false;
9615 
9616  if (Diagnose) {
9617  auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9618  S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9619  << llvm::to_underlying(getEffectiveCSM()) << ParentClass
9620  << /*IsField*/ true << FD << 4 << /*IsDtorCallInCtor*/ false
9621  << /*IsObjCPtr*/ true;
9622  }
9623 
9624  return true;
9625 }
9626 
9627 /// Check whether we should delete a special member function due to the class
9628 /// having a particular direct or virtual base class.
9629 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9630  CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9631  // If program is correct, BaseClass cannot be null, but if it is, the error
9632  // must be reported elsewhere.
9633  if (!BaseClass)
9634  return false;
9635  // If we have an inheriting constructor, check whether we're calling an
9636  // inherited constructor instead of a default constructor.
9637  Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9638  if (auto *BaseCtor = SMOR.getMethod()) {
9639  // Note that we do not check access along this path; other than that,
9640  // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9641  // FIXME: Check that the base has a usable destructor! Sink this into
9642  // shouldDeleteForClassSubobject.
9643  if (BaseCtor->isDeleted() && Diagnose) {
9644  S.Diag(Base->getBeginLoc(),
9645  diag::note_deleted_special_member_class_subobject)
9646  << llvm::to_underlying(getEffectiveCSM()) << MD->getParent()
9647  << /*IsField*/ false << Base->getType() << /*Deleted*/ 1
9648  << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ false;
9649  S.NoteDeletedFunction(BaseCtor);
9650  }
9651  return BaseCtor->isDeleted();
9652  }
9653  return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9654 }
9655 
9656 /// Check whether we should delete a special member function due to the class
9657 /// having a particular non-static data member.
9658 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9659  QualType FieldType = S.Context.getBaseElementType(FD->getType());
9660  CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9661 
9662  if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9663  return true;
9664 
9666  // For a default constructor, all references must be initialized in-class
9667  // and, if a union, it must have a non-const member.
9668  if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9669  if (Diagnose)
9670  S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9671  << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9672  return true;
9673  }
9674  // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9675  // data member of const-qualified type (or array thereof) with no
9676  // brace-or-equal-initializer is not const-default-constructible.
9677  if (!inUnion() && FieldType.isConstQualified() &&
9678  !FD->hasInClassInitializer() &&
9679  (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9680  if (Diagnose)
9681  S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9682  << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9683  return true;
9684  }
9685 
9686  if (inUnion() && !FieldType.isConstQualified())
9687  AllFieldsAreConst = false;
9688  } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
9689  // For a copy constructor, data members must not be of rvalue reference
9690  // type.
9691  if (FieldType->isRValueReferenceType()) {
9692  if (Diagnose)
9693  S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9694  << MD->getParent() << FD << FieldType;
9695  return true;
9696  }
9697  } else if (IsAssignment) {
9698  // For an assignment operator, data members must not be of reference type.
9699  if (FieldType->isReferenceType()) {
9700  if (Diagnose)
9701  S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9702  << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9703  return true;
9704  }
9705  if (!FieldRecord && FieldType.isConstQualified()) {
9706  // C++11 [class.copy]p23:
9707  // -- a non-static data member of const non-class type (or array thereof)
9708  if (Diagnose)
9709  S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9710  << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9711  return true;
9712  }
9713  }
9714 
9715  if (FieldRecord) {
9716  // Some additional restrictions exist on the variant members.
9717  if (!inUnion() && FieldRecord->isUnion() &&
9718  FieldRecord->isAnonymousStructOrUnion()) {
9719  bool AllVariantFieldsAreConst = true;
9720 
9721  // FIXME: Handle anonymous unions declared within anonymous unions.
9722  for (auto *UI : FieldRecord->fields()) {
9723  QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9724 
9725  if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9726  return true;
9727 
9728  if (!UnionFieldType.isConstQualified())
9729  AllVariantFieldsAreConst = false;
9730 
9731  CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9732  if (UnionFieldRecord &&
9733  shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9734  UnionFieldType.getCVRQualifiers()))
9735  return true;
9736  }
9737 
9738  // At least one member in each anonymous union must be non-const
9740  AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
9741  if (Diagnose)
9742  S.Diag(FieldRecord->getLocation(),
9743  diag::note_deleted_default_ctor_all_const)
9744  << !!ICI << MD->getParent() << /*anonymous union*/1;
9745  return true;
9746  }
9747 
9748  // Don't check the implicit member of the anonymous union type.
9749  // This is technically non-conformant but supported, and we have a
9750  // diagnostic for this elsewhere.
9751  return false;
9752  }
9753 
9754  if (shouldDeleteForClassSubobject(FieldRecord, FD,
9755  FieldType.getCVRQualifiers()))
9756  return true;
9757  }
9758 
9759  return false;
9760 }
9761 
9762 /// C++11 [class.ctor] p5:
9763 /// A defaulted default constructor for a class X is defined as deleted if
9764 /// X is a union and all of its variant members are of const-qualified type.
9765 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9766  // This is a silly definition, because it gives an empty union a deleted
9767  // default constructor. Don't do that.
9768  if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
9769  AllFieldsAreConst) {
9770  bool AnyFields = false;
9771  for (auto *F : MD->getParent()->fields())
9772  if ((AnyFields = !F->isUnnamedBitField()))
9773  break;
9774  if (!AnyFields)
9775  return false;
9776  if (Diagnose)
9777  S.Diag(MD->getParent()->getLocation(),
9778  diag::note_deleted_default_ctor_all_const)
9779  << !!ICI << MD->getParent() << /*not anonymous union*/0;
9780  return true;
9781  }
9782  return false;
9783 }
9784 
9785 /// Determine whether a defaulted special member function should be defined as
9786 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9787 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9791  bool Diagnose) {
9792  if (MD->isInvalidDecl())
9793  return false;
9794  CXXRecordDecl *RD = MD->getParent();
9795  assert(!RD->isDependentType() && "do deletion after instantiation");
9796  if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
9797  RD->isInvalidDecl())
9798  return false;
9799 
9800  // C++11 [expr.lambda.prim]p19:
9801  // The closure type associated with a lambda-expression has a
9802  // deleted (8.4.3) default constructor and a deleted copy
9803  // assignment operator.
9804  // C++2a adds back these operators if the lambda has no lambda-capture.
9808  if (Diagnose)
9809  Diag(RD->getLocation(), diag::note_lambda_decl);
9810  return true;
9811  }
9812 
9813  // For an anonymous struct or union, the copy and assignment special members
9814  // will never be used, so skip the check. For an anonymous union declared at
9815  // namespace scope, the constructor and destructor are used.
9818  return false;
9819 
9820  // C++11 [class.copy]p7, p18:
9821  // If the class definition declares a move constructor or move assignment
9822  // operator, an implicitly declared copy constructor or copy assignment
9823  // operator is defined as deleted.
9824  if (MD->isImplicit() && (CSM == CXXSpecialMemberKind::CopyConstructor ||
9826  CXXMethodDecl *UserDeclaredMove = nullptr;
9827 
9828  // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9829  // deletion of the corresponding copy operation, not both copy operations.
9830  // MSVC 2015 has adopted the standards conforming behavior.
9831  bool DeletesOnlyMatchingCopy =
9832  getLangOpts().MSVCCompat &&
9834 
9835  if (RD->hasUserDeclaredMoveConstructor() &&
9836  (!DeletesOnlyMatchingCopy ||
9838  if (!Diagnose) return true;
9839 
9840  // Find any user-declared move constructor.
9841  for (auto *I : RD->ctors()) {
9842  if (I->isMoveConstructor()) {
9843  UserDeclaredMove = I;
9844  break;
9845  }
9846  }
9847  assert(UserDeclaredMove);
9848  } else if (RD->hasUserDeclaredMoveAssignment() &&
9849  (!DeletesOnlyMatchingCopy ||
9851  if (!Diagnose) return true;
9852 
9853  // Find any user-declared move assignment operator.
9854  for (auto *I : RD->methods()) {
9855  if (I->isMoveAssignmentOperator()) {
9856  UserDeclaredMove = I;
9857  break;
9858  }
9859  }
9860  assert(UserDeclaredMove);
9861  }
9862 
9863  if (UserDeclaredMove) {
9864  Diag(UserDeclaredMove->getLocation(),
9865  diag::note_deleted_copy_user_declared_move)
9866  << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
9867  << UserDeclaredMove->isMoveAssignmentOperator();
9868  return true;
9869  }
9870  }
9871 
9872  // Do access control from the special member function
9873  ContextRAII MethodContext(*this, MD);
9874 
9875  // C++11 [class.dtor]p5:
9876  // -- for a virtual destructor, lookup of the non-array deallocation function
9877  // results in an ambiguity or in a function that is deleted or inaccessible
9878  if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
9879  FunctionDecl *OperatorDelete = nullptr;
9880  DeclarationName Name =
9882  if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9883  OperatorDelete, /*Diagnose*/false)) {
9884  if (Diagnose)
9885  Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9886  return true;
9887  }
9888  }
9889 
9890  SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9891 
9892  // Per DR1611, do not consider virtual bases of constructors of abstract
9893  // classes, since we are not going to construct them.
9894  // Per DR1658, do not consider virtual bases of destructors of abstract
9895  // classes either.
9896  // Per DR2180, for assignment operators we only assign (and thus only
9897  // consider) direct bases.
9898  if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9899  : SMI.VisitPotentiallyConstructedBases))
9900  return true;
9901 
9902  if (SMI.shouldDeleteForAllConstMembers())
9903  return true;
9904 
9905  if (getLangOpts().CUDA) {
9906  // We should delete the special member in CUDA mode if target inference
9907  // failed.
9908  // For inherited constructors (non-null ICI), CSM may be passed so that MD
9909  // is treated as certain special member, which may not reflect what special
9910  // member MD really is. However inferTargetForImplicitSpecialMember
9911  // expects CSM to match MD, therefore recalculate CSM.
9912  assert(ICI || CSM == getSpecialMember(MD));
9913  auto RealCSM = CSM;
9914  if (ICI)
9915  RealCSM = getSpecialMember(MD);
9916 
9917  return CUDA().inferTargetForImplicitSpecialMember(RD, RealCSM, MD,
9918  SMI.ConstArg, Diagnose);
9919  }
9920 
9921  return false;
9922 }
9923 
9926  assert(DFK && "not a defaultable function");
9927  assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9928 
9929  if (DFK.isSpecialMember()) {
9930  ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9931  nullptr, /*Diagnose=*/true);
9932  } else {
9933  DefaultedComparisonAnalyzer(
9934  *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9935  DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9936  .visit();
9937  }
9938 }
9939 
9940 /// Perform lookup for a special member of the specified kind, and determine
9941 /// whether it is trivial. If the triviality can be determined without the
9942 /// lookup, skip it. This is intended for use when determining whether a
9943 /// special member of a containing object is trivial, and thus does not ever
9944 /// perform overload resolution for default constructors.
9945 ///
9946 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9947 /// member that was most likely to be intended to be trivial, if any.
9948 ///
9949 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9950 /// determine whether the special member is trivial.
9952  CXXSpecialMemberKind CSM, unsigned Quals,
9953  bool ConstRHS,
9955  CXXMethodDecl **Selected) {
9956  if (Selected)
9957  *Selected = nullptr;
9958 
9959  switch (CSM) {
9961  llvm_unreachable("not a special member");
9962 
9964  // C++11 [class.ctor]p5:
9965  // A default constructor is trivial if:
9966  // - all the [direct subobjects] have trivial default constructors
9967  //
9968  // Note, no overload resolution is performed in this case.
9969  if (RD->hasTrivialDefaultConstructor())
9970  return true;
9971 
9972  if (Selected) {
9973  // If there's a default constructor which could have been trivial, dig it
9974  // out. Otherwise, if there's any user-provided default constructor, point
9975  // to that as an example of why there's not a trivial one.
9976  CXXConstructorDecl *DefCtor = nullptr;
9979  for (auto *CI : RD->ctors()) {
9980  if (!CI->isDefaultConstructor())
9981  continue;
9982  DefCtor = CI;
9983  if (!DefCtor->isUserProvided())
9984  break;
9985  }
9986 
9987  *Selected = DefCtor;
9988  }
9989 
9990  return false;
9991 
9993  // C++11 [class.dtor]p5:
9994  // A destructor is trivial if:
9995  // - all the direct [subobjects] have trivial destructors
9996  if (RD->hasTrivialDestructor() ||
9997  (TAH == Sema::TAH_ConsiderTrivialABI &&
9999  return true;
10000 
10001  if (Selected) {
10002  if (RD->needsImplicitDestructor())
10004  *Selected = RD->getDestructor();
10005  }
10006 
10007  return false;
10008 
10010  // C++11 [class.copy]p12:
10011  // A copy constructor is trivial if:
10012  // - the constructor selected to copy each direct [subobject] is trivial
10013  if (RD->hasTrivialCopyConstructor() ||
10014  (TAH == Sema::TAH_ConsiderTrivialABI &&
10016  if (Quals == Qualifiers::Const)
10017  // We must either select the trivial copy constructor or reach an
10018  // ambiguity; no need to actually perform overload resolution.
10019  return true;
10020  } else if (!Selected) {
10021  return false;
10022  }
10023  // In C++98, we are not supposed to perform overload resolution here, but we
10024  // treat that as a language defect, as suggested on cxx-abi-dev, to treat
10025  // cases like B as having a non-trivial copy constructor:
10026  // struct A { template<typename T> A(T&); };
10027  // struct B { mutable A a; };
10028  goto NeedOverloadResolution;
10029 
10031  // C++11 [class.copy]p25:
10032  // A copy assignment operator is trivial if:
10033  // - the assignment operator selected to copy each direct [subobject] is
10034  // trivial
10035  if (RD->hasTrivialCopyAssignment()) {
10036  if (Quals == Qualifiers::Const)
10037  return true;
10038  } else if (!Selected) {
10039  return false;
10040  }
10041  // In C++98, we are not supposed to perform overload resolution here, but we
10042  // treat that as a language defect.
10043  goto NeedOverloadResolution;
10044 
10047  NeedOverloadResolution:
10049  lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
10050 
10051  // The standard doesn't describe how to behave if the lookup is ambiguous.
10052  // We treat it as not making the member non-trivial, just like the standard
10053  // mandates for the default constructor. This should rarely matter, because
10054  // the member will also be deleted.
10056  return true;
10057 
10058  if (!SMOR.getMethod()) {
10059  assert(SMOR.getKind() ==
10061  return false;
10062  }
10063 
10064  // We deliberately don't check if we found a deleted special member. We're
10065  // not supposed to!
10066  if (Selected)
10067  *Selected = SMOR.getMethod();
10068 
10069  if (TAH == Sema::TAH_ConsiderTrivialABI &&
10072  return SMOR.getMethod()->isTrivialForCall();
10073  return SMOR.getMethod()->isTrivial();
10074  }
10075 
10076  llvm_unreachable("unknown special method kind");
10077 }
10078 
10080  for (auto *CI : RD->ctors())
10081  if (!CI->isImplicit())
10082  return CI;
10083 
10084  // Look for constructor templates.
10085  typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
10086  for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
10087  if (CXXConstructorDecl *CD =
10088  dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
10089  return CD;
10090  }
10091 
10092  return nullptr;
10093 }
10094 
10095 /// The kind of subobject we are checking for triviality. The values of this
10096 /// enumeration are used in diagnostics.
10098  /// The subobject is a base class.
10100  /// The subobject is a non-static data member.
10102  /// The object is actually the complete object.
10104 };
10105 
10106 /// Check whether the special member selected for a given type would be trivial.
10108  QualType SubType, bool ConstRHS,
10112  bool Diagnose) {
10113  CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
10114  if (!SubRD)
10115  return true;
10116 
10117  CXXMethodDecl *Selected;
10118  if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
10119  ConstRHS, TAH, Diagnose ? &Selected : nullptr))
10120  return true;
10121 
10122  if (Diagnose) {
10123  if (ConstRHS)
10124  SubType.addConst();
10125 
10126  if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
10127  S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
10128  << Kind << SubType.getUnqualifiedType();
10129  if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
10130  S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
10131  } else if (!Selected)
10132  S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
10133  << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM)
10134  << SubType;
10135  else if (Selected->isUserProvided()) {
10136  if (Kind == TSK_CompleteObject)
10137  S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
10138  << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM);
10139  else {
10140  S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
10141  << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM);
10142  S.Diag(Selected->getLocation(), diag::note_declared_at);
10143  }
10144  } else {
10145  if (Kind != TSK_CompleteObject)
10146  S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
10147  << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM);
10148 
10149  // Explain why the defaulted or deleted special member isn't trivial.
10151  Diagnose);
10152  }
10153  }
10154 
10155  return false;
10156 }
10157 
10158 /// Check whether the members of a class type allow a special member to be
10159 /// trivial.
10161  CXXSpecialMemberKind CSM, bool ConstArg,
10163  bool Diagnose) {
10164  for (const auto *FI : RD->fields()) {
10165  if (FI->isInvalidDecl() || FI->isUnnamedBitField())
10166  continue;
10167 
10168  QualType FieldType = S.Context.getBaseElementType(FI->getType());
10169 
10170  // Pretend anonymous struct or union members are members of this class.
10171  if (FI->isAnonymousStructOrUnion()) {
10172  if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
10173  CSM, ConstArg, TAH, Diagnose))
10174  return false;
10175  continue;
10176  }
10177 
10178  // C++11 [class.ctor]p5:
10179  // A default constructor is trivial if [...]
10180  // -- no non-static data member of its class has a
10181  // brace-or-equal-initializer
10183  FI->hasInClassInitializer()) {
10184  if (Diagnose)
10185  S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
10186  << FI;
10187  return false;
10188  }
10189 
10190  // Objective C ARC 4.3.5:
10191  // [...] nontrivally ownership-qualified types are [...] not trivially
10192  // default constructible, copy constructible, move constructible, copy
10193  // assignable, move assignable, or destructible [...]
10194  if (FieldType.hasNonTrivialObjCLifetime()) {
10195  if (Diagnose)
10196  S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
10197  << RD << FieldType.getObjCLifetime();
10198  return false;
10199  }
10200 
10201  bool ConstRHS = ConstArg && !FI->isMutable();
10202  if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
10203  CSM, TSK_Field, TAH, Diagnose))
10204  return false;
10205  }
10206 
10207  return true;
10208 }
10209 
10210 /// Diagnose why the specified class does not have a trivial special member of
10211 /// the given kind.
10213  CXXSpecialMemberKind CSM) {
10214  QualType Ty = Context.getRecordType(RD);
10215 
10216  bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10218  checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
10220  /*Diagnose*/true);
10221 }
10222 
10223 /// Determine whether a defaulted or deleted special member function is trivial,
10224 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
10225 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
10227  TrivialABIHandling TAH, bool Diagnose) {
10228  assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10229  "not special enough");
10230 
10231  CXXRecordDecl *RD = MD->getParent();
10232 
10233  bool ConstArg = false;
10234 
10235  // C++11 [class.copy]p12, p25: [DR1593]
10236  // A [special member] is trivial if [...] its parameter-type-list is
10237  // equivalent to the parameter-type-list of an implicit declaration [...]
10238  switch (CSM) {
10241  // Trivial default constructors and destructors cannot have parameters.
10242  break;
10243 
10246  const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10247  const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10248 
10249  // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10250  // if they are not user-provided and their parameter-type-list is equivalent
10251  // to the parameter-type-list of an implicit declaration. This maintains the
10252  // behavior before dr2171 was implemented.
10253  //
10254  // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10255  // trivial, if they are not user-provided, regardless of the qualifiers on
10256  // the reference type.
10257  const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=
10259  if (!RT ||
10261  ClangABICompat14)) {
10262  if (Diagnose)
10263  Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10264  << Param0->getSourceRange() << Param0->getType()
10267  return false;
10268  }
10269 
10270  ConstArg = RT->getPointeeType().isConstQualified();
10271  break;
10272  }
10273 
10276  // Trivial move operations always have non-cv-qualified parameters.
10277  const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10278  const RValueReferenceType *RT =
10279  Param0->getType()->getAs<RValueReferenceType>();
10280  if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10281  if (Diagnose)
10282  Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10283  << Param0->getSourceRange() << Param0->getType()
10285  return false;
10286  }
10287  break;
10288  }
10289 
10291  llvm_unreachable("not a special member");
10292  }
10293 
10294  if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10295  if (Diagnose)
10297  diag::note_nontrivial_default_arg)
10299  return false;
10300  }
10301  if (MD->isVariadic()) {
10302  if (Diagnose)
10303  Diag(MD->getLocation(), diag::note_nontrivial_variadic);
10304  return false;
10305  }
10306 
10307  // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10308  // A copy/move [constructor or assignment operator] is trivial if
10309  // -- the [member] selected to copy/move each direct base class subobject
10310  // is trivial
10311  //
10312  // C++11 [class.copy]p12, C++11 [class.copy]p25:
10313  // A [default constructor or destructor] is trivial if
10314  // -- all the direct base classes have trivial [default constructors or
10315  // destructors]
10316  for (const auto &BI : RD->bases())
10317  if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
10318  ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
10319  return false;
10320 
10321  // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10322  // A copy/move [constructor or assignment operator] for a class X is
10323  // trivial if
10324  // -- for each non-static data member of X that is of class type (or array
10325  // thereof), the constructor selected to copy/move that member is
10326  // trivial
10327  //
10328  // C++11 [class.copy]p12, C++11 [class.copy]p25:
10329  // A [default constructor or destructor] is trivial if
10330  // -- for all of the non-static data members of its class that are of class
10331  // type (or array thereof), each such class has a trivial [default
10332  // constructor or destructor]
10333  if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
10334  return false;
10335 
10336  // C++11 [class.dtor]p5:
10337  // A destructor is trivial if [...]
10338  // -- the destructor is not virtual
10339  if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10340  if (Diagnose)
10341  Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
10342  return false;
10343  }
10344 
10345  // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10346  // A [special member] for class X is trivial if [...]
10347  // -- class X has no virtual functions and no virtual base classes
10348  if (CSM != CXXSpecialMemberKind::Destructor &&
10349  MD->getParent()->isDynamicClass()) {
10350  if (!Diagnose)
10351  return false;
10352 
10353  if (RD->getNumVBases()) {
10354  // Check for virtual bases. We already know that the corresponding
10355  // member in all bases is trivial, so vbases must all be direct.
10356  CXXBaseSpecifier &BS = *RD->vbases_begin();
10357  assert(BS.isVirtual());
10358  Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
10359  return false;
10360  }
10361 
10362  // Must have a virtual method.
10363  for (const auto *MI : RD->methods()) {
10364  if (MI->isVirtual()) {
10365  SourceLocation MLoc = MI->getBeginLoc();
10366  Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
10367  return false;
10368  }
10369  }
10370 
10371  llvm_unreachable("dynamic class with no vbases and no virtual functions");
10372  }
10373 
10374  // Looks like it's trivial!
10375  return true;
10376 }
10377 
10378 namespace {
10379 struct FindHiddenVirtualMethod {
10380  Sema *S;
10381  CXXMethodDecl *Method;
10382  llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10383  SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10384 
10385 private:
10386  /// Check whether any most overridden method from MD in Methods
10387  static bool CheckMostOverridenMethods(
10388  const CXXMethodDecl *MD,
10389  const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10390  if (MD->size_overridden_methods() == 0)
10391  return Methods.count(MD->getCanonicalDecl());
10392  for (const CXXMethodDecl *O : MD->overridden_methods())
10393  if (CheckMostOverridenMethods(O, Methods))
10394  return true;
10395  return false;
10396  }
10397 
10398 public:
10399  /// Member lookup function that determines whether a given C++
10400  /// method overloads virtual methods in a base class without overriding any,
10401  /// to be used with CXXRecordDecl::lookupInBases().
10402  bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10403  RecordDecl *BaseRecord =
10404  Specifier->getType()->castAs<RecordType>()->getDecl();
10405 
10406  DeclarationName Name = Method->getDeclName();
10407  assert(Name.getNameKind() == DeclarationName::Identifier);
10408 
10409  bool foundSameNameMethod = false;
10410  SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10411  for (Path.Decls = BaseRecord->lookup(Name).begin();
10412  Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10413  NamedDecl *D = *Path.Decls;
10414  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
10415  MD = MD->getCanonicalDecl();
10416  foundSameNameMethod = true;
10417  // Interested only in hidden virtual methods.
10418  if (!MD->isVirtual())
10419  continue;
10420  // If the method we are checking overrides a method from its base
10421  // don't warn about the other overloaded methods. Clang deviates from
10422  // GCC by only diagnosing overloads of inherited virtual functions that
10423  // do not override any other virtual functions in the base. GCC's
10424  // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10425  // function from a base class. These cases may be better served by a
10426  // warning (not specific to virtual functions) on call sites when the
10427  // call would select a different function from the base class, were it
10428  // visible.
10429  // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10430  if (!S->IsOverload(Method, MD, false))
10431  return true;
10432  // Collect the overload only if its hidden.
10433  if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
10434  overloadedMethods.push_back(MD);
10435  }
10436  }
10437 
10438  if (foundSameNameMethod)
10439  OverloadedMethods.append(overloadedMethods.begin(),
10440  overloadedMethods.end());
10441  return foundSameNameMethod;
10442  }
10443 };
10444 } // end anonymous namespace
10445 
10446 /// Add the most overridden methods from MD to Methods
10448  llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10449  if (MD->size_overridden_methods() == 0)
10450  Methods.insert(MD->getCanonicalDecl());
10451  else
10452  for (const CXXMethodDecl *O : MD->overridden_methods())
10453  AddMostOverridenMethods(O, Methods);
10454 }
10455 
10456 /// Check if a method overloads virtual methods in a base class without
10457 /// overriding any.
10459  SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10460  if (!MD->getDeclName().isIdentifier())
10461  return;
10462 
10463  CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10464  /*bool RecordPaths=*/false,
10465  /*bool DetectVirtual=*/false);
10466  FindHiddenVirtualMethod FHVM;
10467  FHVM.Method = MD;
10468  FHVM.S = this;
10469 
10470  // Keep the base methods that were overridden or introduced in the subclass
10471  // by 'using' in a set. A base method not in this set is hidden.
10472  CXXRecordDecl *DC = MD->getParent();
10474  for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
10475  NamedDecl *ND = *I;
10476  if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
10477  ND = shad->getTargetDecl();
10478  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10479  AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10480  }
10481 
10482  if (DC->lookupInBases(FHVM, Paths))
10483  OverloadedMethods = FHVM.OverloadedMethods;
10484 }
10485 
10487  SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10488  for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
10489  CXXMethodDecl *overloadedMD = OverloadedMethods[i];
10490  PartialDiagnostic PD = PDiag(
10491  diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10492  HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10493  Diag(overloadedMD->getLocation(), PD);
10494  }
10495 }
10496 
10497 /// Diagnose methods which overload virtual methods in a base class
10498 /// without overriding any.
10500  if (MD->isInvalidDecl())
10501  return;
10502 
10503  if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10504  return;
10505 
10506  SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10507  FindHiddenVirtualMethods(MD, OverloadedMethods);
10508  if (!OverloadedMethods.empty()) {
10509  Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10510  << MD << (OverloadedMethods.size() > 1);
10511 
10512  NoteHiddenVirtualMethods(MD, OverloadedMethods);
10513  }
10514 }
10515 
10517  auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10518  // No diagnostics if this is a template instantiation.
10520  Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10521  diag::ext_cannot_use_trivial_abi) << &RD;
10522  Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10523  diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10524  }
10525  RD.dropAttr<TrivialABIAttr>();
10526  };
10527 
10528  // Ill-formed if the copy and move constructors are deleted.
10529  auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10530  // If the type is dependent, then assume it might have
10531  // implicit copy or move ctor because we won't know yet at this point.
10532  if (RD.isDependentType())
10533  return true;
10534  if (RD.needsImplicitCopyConstructor() &&
10536  return true;
10537  if (RD.needsImplicitMoveConstructor() &&
10539  return true;
10540  for (const CXXConstructorDecl *CD : RD.ctors())
10541  if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10542  return true;
10543  return false;
10544  };
10545 
10546  if (!HasNonDeletedCopyOrMoveConstructor()) {
10547  PrintDiagAndRemoveAttr(0);
10548  return;
10549  }
10550 
10551  // Ill-formed if the struct has virtual functions.
10552  if (RD.isPolymorphic()) {
10553  PrintDiagAndRemoveAttr(1);
10554  return;
10555  }
10556 
10557  for (const auto &B : RD.bases()) {
10558  // Ill-formed if the base class is non-trivial for the purpose of calls or a
10559  // virtual base.
10560  if (!B.getType()->isDependentType() &&
10561  !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10562  PrintDiagAndRemoveAttr(2);
10563  return;
10564  }
10565 
10566  if (B.isVirtual()) {
10567  PrintDiagAndRemoveAttr(3);
10568  return;
10569  }
10570  }
10571 
10572  for (const auto *FD : RD.fields()) {
10573  // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10574  // non-trivial for the purpose of calls.
10575  QualType FT = FD->getType();
10576  if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
10577  PrintDiagAndRemoveAttr(4);
10578  return;
10579  }
10580 
10581  if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10582  if (!RT->isDependentType() &&
10583  !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10584  PrintDiagAndRemoveAttr(5);
10585  return;
10586  }
10587  }
10588 }
10589 
10591  Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
10592  SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10593  if (!TagDecl)
10594  return;
10595 
10597 
10598  for (const ParsedAttr &AL : AttrList) {
10599  if (AL.getKind() != ParsedAttr::AT_Visibility)
10600  continue;
10601  AL.setInvalid();
10602  Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10603  }
10604 
10605  ActOnFields(S, RLoc, TagDecl,
10607  // strict aliasing violation!
10608  reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10609  FieldCollector->getCurNumFields()),
10610  LBrac, RBrac, AttrList);
10611 
10612  CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
10613 }
10614 
10615 /// Find the equality comparison functions that should be implicitly declared
10616 /// in a given class definition, per C++2a [class.compare.default]p3.
10618  ASTContext &Ctx, CXXRecordDecl *RD,
10620  DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10621  if (!RD->lookup(EqEq).empty())
10622  // Member operator== explicitly declared: no implicit operator==s.
10623  return;
10624 
10625  // Traverse friends looking for an '==' or a '<=>'.
10626  for (FriendDecl *Friend : RD->friends()) {
10627  FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10628  if (!FD) continue;
10629 
10630  if (FD->getOverloadedOperator() == OO_EqualEqual) {
10631  // Friend operator== explicitly declared: no implicit operator==s.
10632  Spaceships.clear();
10633  return;
10634  }
10635 
10636  if (FD->getOverloadedOperator() == OO_Spaceship &&
10637  FD->isExplicitlyDefaulted())
10638  Spaceships.push_back(FD);
10639  }
10640 
10641  // Look for members named 'operator<=>'.
10642  DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10643  for (NamedDecl *ND : RD->lookup(Cmp)) {
10644  // Note that we could find a non-function here (either a function template
10645  // or a using-declaration). Neither case results in an implicit
10646  // 'operator=='.
10647  if (auto *FD = dyn_cast<FunctionDecl>(ND))
10648  if (FD->isExplicitlyDefaulted())
10649  Spaceships.push_back(FD);
10650  }
10651 }
10652 
10653 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
10654 /// special functions, such as the default constructor, copy
10655 /// constructor, or destructor, to the given C++ class (C++
10656 /// [special]p1). This routine can only be executed just before the
10657 /// definition of the class is complete.
10659  // Don't add implicit special members to templated classes.
10660  // FIXME: This means unqualified lookups for 'operator=' within a class
10661  // template don't work properly.
10662  if (!ClassDecl->isDependentType()) {
10663  if (ClassDecl->needsImplicitDefaultConstructor()) {
10665 
10666  if (ClassDecl->hasInheritedConstructor())
10668  }
10669 
10670  if (ClassDecl->needsImplicitCopyConstructor()) {
10672 
10673  // If the properties or semantics of the copy constructor couldn't be
10674  // determined while the class was being declared, force a declaration
10675  // of it now.
10676  if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10677  ClassDecl->hasInheritedConstructor())
10678  DeclareImplicitCopyConstructor(ClassDecl);
10679  // For the MS ABI we need to know whether the copy ctor is deleted. A
10680  // prerequisite for deleting the implicit copy ctor is that the class has
10681  // a move ctor or move assignment that is either user-declared or whose
10682  // semantics are inherited from a subobject. FIXME: We should provide a
10683  // more direct way for CodeGen to ask whether the constructor was deleted.
10684  else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10685  (ClassDecl->hasUserDeclaredMoveConstructor() ||
10687  ClassDecl->hasUserDeclaredMoveAssignment() ||
10689  DeclareImplicitCopyConstructor(ClassDecl);
10690  }
10691 
10692  if (getLangOpts().CPlusPlus11 &&
10693  ClassDecl->needsImplicitMoveConstructor()) {
10695 
10696  if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10697  ClassDecl->hasInheritedConstructor())
10698  DeclareImplicitMoveConstructor(ClassDecl);
10699  }
10700 
10701  if (ClassDecl->needsImplicitCopyAssignment()) {
10703 
10704  // If we have a dynamic class, then the copy assignment operator may be
10705  // virtual, so we have to declare it immediately. This ensures that, e.g.,
10706  // it shows up in the right place in the vtable and that we diagnose
10707  // problems with the implicit exception specification.
10708  if (ClassDecl->isDynamicClass() ||
10710  ClassDecl->hasInheritedAssignment())
10711  DeclareImplicitCopyAssignment(ClassDecl);
10712  }
10713 
10714  if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10716 
10717  // Likewise for the move assignment operator.
10718  if (ClassDecl->isDynamicClass() ||
10720  ClassDecl->hasInheritedAssignment())
10721  DeclareImplicitMoveAssignment(ClassDecl);
10722  }
10723 
10724  if (ClassDecl->needsImplicitDestructor()) {
10726 
10727  // If we have a dynamic class, then the destructor may be virtual, so we
10728  // have to declare the destructor immediately. This ensures that, e.g., it
10729  // shows up in the right place in the vtable and that we diagnose problems
10730  // with the implicit exception specification.
10731  if (ClassDecl->isDynamicClass() ||
10733  DeclareImplicitDestructor(ClassDecl);
10734  }
10735  }
10736 
10737  // C++2a [class.compare.default]p3:
10738  // If the member-specification does not explicitly declare any member or
10739  // friend named operator==, an == operator function is declared implicitly
10740  // for each defaulted three-way comparison operator function defined in
10741  // the member-specification
10742  // FIXME: Consider doing this lazily.
10743  // We do this during the initial parse for a class template, not during
10744  // instantiation, so that we can handle unqualified lookups for 'operator=='
10745  // when parsing the template.
10747  llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10749  DefaultedSpaceships);
10750  for (auto *FD : DefaultedSpaceships)
10751  DeclareImplicitEqualityComparison(ClassDecl, FD);
10752  }
10753 }
10754 
10755 unsigned
10757  llvm::function_ref<Scope *()> EnterScope) {
10758  if (!D)
10759  return 0;
10761 
10762  // In order to get name lookup right, reenter template scopes in order from
10763  // outermost to innermost.
10765  DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10766 
10767  if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10768  for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10769  ParameterLists.push_back(DD->getTemplateParameterList(i));
10770 
10771  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10772  if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10773  ParameterLists.push_back(FTD->getTemplateParameters());
10774  } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10775  LookupDC = VD->getDeclContext();
10776 
10777  if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10778  ParameterLists.push_back(VTD->getTemplateParameters());
10779  else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10780  ParameterLists.push_back(PSD->getTemplateParameters());
10781  }
10782  } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10783  for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10784  ParameterLists.push_back(TD->getTemplateParameterList(i));
10785 
10786  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10788  ParameterLists.push_back(CTD->getTemplateParameters());
10789  else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10790  ParameterLists.push_back(PSD->getTemplateParameters());
10791  }
10792  }
10793  // FIXME: Alias declarations and concepts.
10794 
10795  unsigned Count = 0;
10796  Scope *InnermostTemplateScope = nullptr;
10797  for (TemplateParameterList *Params : ParameterLists) {
10798  // Ignore explicit specializations; they don't contribute to the template
10799  // depth.
10800  if (Params->size() == 0)
10801  continue;
10802 
10803  InnermostTemplateScope = EnterScope();
10804  for (NamedDecl *Param : *Params) {
10805  if (Param->getDeclName()) {
10806  InnermostTemplateScope->AddDecl(Param);
10807  IdResolver.AddDecl(Param);
10808  }
10809  }
10810  ++Count;
10811  }
10812 
10813  // Associate the new template scopes with the corresponding entities.
10814  if (InnermostTemplateScope) {
10815  assert(LookupDC && "no enclosing DeclContext for template lookup");
10816  EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10817  }
10818 
10819  return Count;
10820 }
10821 
10823  if (!RecordD) return;
10824  AdjustDeclIfTemplate(RecordD);
10825  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10826  PushDeclContext(S, Record);
10827 }
10828 
10830  if (!RecordD) return;
10831  PopDeclContext();
10832 }
10833 
10834 /// This is used to implement the constant expression evaluation part of the
10835 /// attribute enable_if extension. There is nothing in standard C++ which would
10836 /// require reentering parameters.
10838  if (!Param)
10839  return;
10840 
10841  S->AddDecl(Param);
10842  if (Param->getDeclName())
10843  IdResolver.AddDecl(Param);
10844 }
10845 
10846 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
10847 /// parsing a top-level (non-nested) C++ class, and we are now
10848 /// parsing those parts of the given Method declaration that could
10849 /// not be parsed earlier (C++ [class.mem]p2), such as default
10850 /// arguments. This action should enter the scope of the given
10851 /// Method declaration as if we had just parsed the qualified method
10852 /// name. However, it should not bring the parameters into scope;
10853 /// that will be performed by ActOnDelayedCXXMethodParameter.
10855 }
10856 
10857 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10858 /// C++ method declaration. We're (re-)introducing the given
10859 /// function parameter into scope for use in parsing later parts of
10860 /// the method declaration. For example, we could see an
10861 /// ActOnParamDefaultArgument event for this parameter.
10863  if (!ParamD)
10864  return;
10865 
10866  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10867 
10868  S->AddDecl(Param);
10869  if (Param->getDeclName())
10870  IdResolver.AddDecl(Param);
10871 }
10872 
10873 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10874 /// processing the delayed method declaration for Method. The method
10875 /// declaration is now considered finished. There may be a separate
10876 /// ActOnStartOfFunctionDef action later (not necessarily
10877 /// immediately!) for this method, if it was also defined inside the
10878 /// class body.
10880  if (!MethodD)
10881  return;
10882 
10883  AdjustDeclIfTemplate(MethodD);
10884 
10885  FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10886 
10887  // Now that we have our default arguments, check the constructor
10888  // again. It could produce additional diagnostics or affect whether
10889  // the class has implicitly-declared destructors, among other
10890  // things.
10891  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10892  CheckConstructor(Constructor);
10893 
10894  // Check the default arguments, which we may have added.
10895  if (!Method->isInvalidDecl())
10896  CheckCXXDefaultArguments(Method);
10897 }
10898 
10899 // Emit the given diagnostic for each non-address-space qualifier.
10900 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10901 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10903  if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10904  bool DiagOccured = false;
10906  [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10907  SourceLocation SL) {
10908  // This diagnostic should be emitted on any qualifier except an addr
10909  // space qualifier. However, forEachQualifier currently doesn't visit
10910  // addr space qualifiers, so there's no way to write this condition
10911  // right now; we just diagnose on everything.
10912  S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10913  DiagOccured = true;
10914  });
10915  if (DiagOccured)
10916  D.setInvalidType();
10917  }
10918 }
10919 
10920 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10921 /// the well-formedness of the constructor declarator @p D with type @p
10922 /// R. If there are any errors in the declarator, this routine will
10923 /// emit diagnostics and set the invalid bit to true. In any case, the type
10924 /// will be updated to reflect a well-formed type for the constructor and
10925 /// returned.
10927  StorageClass &SC) {
10928  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10929 
10930  // C++ [class.ctor]p3:
10931  // A constructor shall not be virtual (10.3) or static (9.4). A
10932  // constructor can be invoked for a const, volatile or const
10933  // volatile object. A constructor shall not be declared const,
10934  // volatile, or const volatile (9.3.2).
10935  if (isVirtual) {
10936  if (!D.isInvalidType())
10937  Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10938  << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10939  << SourceRange(D.getIdentifierLoc());
10940  D.setInvalidType();
10941  }
10942  if (SC == SC_Static) {
10943  if (!D.isInvalidType())
10944  Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10945  << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10946  << SourceRange(D.getIdentifierLoc());
10947  D.setInvalidType();
10948  SC = SC_None;
10949  }
10950 
10951  if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10953  diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10957  D.setInvalidType();
10958  }
10959 
10960  checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10961 
10962  // C++0x [class.ctor]p4:
10963  // A constructor shall not be declared with a ref-qualifier.
10965  if (FTI.hasRefQualifier()) {
10966  Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10969  D.setInvalidType();
10970  }
10971 
10972  // Rebuild the function type "R" without any type qualifiers (in
10973  // case any of the errors above fired) and with "void" as the
10974  // return type, since constructors don't have return types.
10975  const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10976  if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10977  return R;
10978 
10980  EPI.TypeQuals = Qualifiers();
10981  EPI.RefQualifier = RQ_None;
10982 
10983  return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10984 }
10985 
10986 /// CheckConstructor - Checks a fully-formed constructor for
10987 /// well-formedness, issuing any diagnostics required. Returns true if
10988 /// the constructor declarator is invalid.
10990  CXXRecordDecl *ClassDecl
10991  = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10992  if (!ClassDecl)
10993  return Constructor->setInvalidDecl();
10994 
10995  // C++ [class.copy]p3:
10996  // A declaration of a constructor for a class X is ill-formed if
10997  // its first parameter is of type (optionally cv-qualified) X and
10998  // either there are no other parameters or else all other
10999  // parameters have default arguments.
11000  if (!Constructor->isInvalidDecl() &&
11001  Constructor->hasOneParamOrDefaultArgs() &&
11002  Constructor->getTemplateSpecializationKind() !=
11004  QualType ParamType = Constructor->getParamDecl(0)->getType();
11005  QualType ClassTy = Context.getTagDeclType(ClassDecl);
11006  if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
11007  SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
11008  const char *ConstRef
11009  = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
11010  : " const &";
11011  Diag(ParamLoc, diag::err_constructor_byvalue_arg)
11012  << FixItHint::CreateInsertion(ParamLoc, ConstRef);
11013 
11014  // FIXME: Rather that making the constructor invalid, we should endeavor
11015  // to fix the type.
11016  Constructor->setInvalidDecl();
11017  }
11018  }
11019 }
11020 
11021 /// CheckDestructor - Checks a fully-formed destructor definition for
11022 /// well-formedness, issuing any diagnostics required. Returns true
11023 /// on error.
11025  CXXRecordDecl *RD = Destructor->getParent();
11026 
11027  if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
11028  SourceLocation Loc;
11029 
11030  if (!Destructor->isImplicit())
11031  Loc = Destructor->getLocation();
11032  else
11033  Loc = RD->getLocation();
11034 
11035  // If we have a virtual destructor, look up the deallocation function
11036  if (FunctionDecl *OperatorDelete =
11038  Expr *ThisArg = nullptr;
11039 
11040  // If the notional 'delete this' expression requires a non-trivial
11041  // conversion from 'this' to the type of a destroying operator delete's
11042  // first parameter, perform that conversion now.
11043  if (OperatorDelete->isDestroyingOperatorDelete()) {
11044  QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
11045  if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
11046  // C++ [class.dtor]p13:
11047  // ... as if for the expression 'delete this' appearing in a
11048  // non-virtual destructor of the destructor's class.
11049  ContextRAII SwitchContext(*this, Destructor);
11050  ExprResult This =
11051  ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
11052  assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
11053  This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
11054  if (This.isInvalid()) {
11055  // FIXME: Register this as a context note so that it comes out
11056  // in the right order.
11057  Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
11058  return true;
11059  }
11060  ThisArg = This.get();
11061  }
11062  }
11063 
11064  DiagnoseUseOfDecl(OperatorDelete, Loc);
11065  MarkFunctionReferenced(Loc, OperatorDelete);
11066  Destructor->setOperatorDelete(OperatorDelete, ThisArg);
11067  }
11068  }
11069 
11070  return false;
11071 }
11072 
11073 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
11074 /// the well-formednes of the destructor declarator @p D with type @p
11075 /// R. If there are any errors in the declarator, this routine will
11076 /// emit diagnostics and set the declarator to invalid. Even if this happens,
11077 /// will be updated to reflect a well-formed type for the destructor and
11078 /// returned.
11080  StorageClass& SC) {
11081  // C++ [class.dtor]p1:
11082  // [...] A typedef-name that names a class is a class-name
11083  // (7.1.3); however, a typedef-name that names a class shall not
11084  // be used as the identifier in the declarator for a destructor
11085  // declaration.
11086  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
11087  if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
11088  Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11089  << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
11090  else if (const TemplateSpecializationType *TST =
11091  DeclaratorType->getAs<TemplateSpecializationType>())
11092  if (TST->isTypeAlias())
11093  Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11094  << DeclaratorType << 1;
11095 
11096  // C++ [class.dtor]p2:
11097  // A destructor is used to destroy objects of its class type. A
11098  // destructor takes no parameters, and no return type can be
11099  // specified for it (not even void). The address of a destructor
11100  // shall not be taken. A destructor shall not be static. A
11101  // destructor can be invoked for a const, volatile or const
11102  // volatile object. A destructor shall not be declared const,
11103  // volatile or const volatile (9.3.2).
11104  if (SC == SC_Static) {
11105  if (!D.isInvalidType())
11106  Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
11107  << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11110 
11111  SC = SC_None;
11112  }
11113  if (!D.isInvalidType()) {
11114  // Destructors don't have return types, but the parser will
11115  // happily parse something like:
11116  //
11117  // class X {
11118  // float ~X();
11119  // };
11120  //
11121  // The return type will be eliminated later.
11122  if (D.getDeclSpec().hasTypeSpecifier())
11123  Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
11125  << SourceRange(D.getIdentifierLoc());
11126  else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11127  diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
11128  SourceLocation(),
11133  D.setInvalidType();
11134  }
11135  }
11136 
11137  checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
11138 
11139  // C++0x [class.dtor]p2:
11140  // A destructor shall not be declared with a ref-qualifier.
11142  if (FTI.hasRefQualifier()) {
11143  Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
11146  D.setInvalidType();
11147  }
11148 
11149  // Make sure we don't have any parameters.
11150  if (FTIHasNonVoidParameters(FTI)) {
11151  Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
11152 
11153  // Delete the parameters.
11154  FTI.freeParams();
11155  D.setInvalidType();
11156  }
11157 
11158  // Make sure the destructor isn't variadic.
11159  if (FTI.isVariadic) {
11160  Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
11161  D.setInvalidType();
11162  }
11163 
11164  // Rebuild the function type "R" without any type qualifiers or
11165  // parameters (in case any of the errors above fired) and with
11166  // "void" as the return type, since destructors don't have return
11167  // types.
11168  if (!D.isInvalidType())
11169  return R;
11170 
11171  const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11173  EPI.Variadic = false;
11174  EPI.TypeQuals = Qualifiers();
11175  EPI.RefQualifier = RQ_None;
11176  return Context.getFunctionType(Context.VoidTy, std::nullopt, EPI);
11177 }
11178 
11179 static void extendLeft(SourceRange &R, SourceRange Before) {
11180  if (Before.isInvalid())
11181  return;
11182  R.setBegin(Before.getBegin());
11183  if (R.getEnd().isInvalid())
11184  R.setEnd(Before.getEnd());
11185 }
11186 
11188  if (After.isInvalid())
11189  return;
11190  if (R.getBegin().isInvalid())
11191  R.setBegin(After.getBegin());
11192  R.setEnd(After.getEnd());
11193 }
11194 
11195 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
11196 /// well-formednes of the conversion function declarator @p D with
11197 /// type @p R. If there are any errors in the declarator, this routine
11198 /// will emit diagnostics and return true. Otherwise, it will return
11199 /// false. Either way, the type @p R will be updated to reflect a
11200 /// well-formed type for the conversion operator.
11202  StorageClass& SC) {
11203  // C++ [class.conv.fct]p1:
11204  // Neither parameter types nor return type can be specified. The
11205  // type of a conversion function (8.3.5) is "function taking no
11206  // parameter returning conversion-type-id."
11207  if (SC == SC_Static) {
11208  if (!D.isInvalidType())
11209  Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
11211  << D.getName().getSourceRange();
11212  D.setInvalidType();
11213  SC = SC_None;
11214  }
11215 
11216  TypeSourceInfo *ConvTSI = nullptr;
11217  QualType ConvType =
11219 
11220  const DeclSpec &DS = D.getDeclSpec();
11221  if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11222  // Conversion functions don't have return types, but the parser will
11223  // happily parse something like:
11224  //
11225  // class X {
11226  // float operator bool();
11227  // };
11228  //
11229  // The return type will be changed later anyway.
11230  Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
11232  << SourceRange(D.getIdentifierLoc());
11233  D.setInvalidType();
11234  } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11235  // It's also plausible that the user writes type qualifiers in the wrong
11236  // place, such as:
11237  // struct S { const operator int(); };
11238  // FIXME: we could provide a fixit to move the qualifiers onto the
11239  // conversion type.
11240  Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
11241  << SourceRange(D.getIdentifierLoc()) << 0;
11242  D.setInvalidType();
11243  }
11244  const auto *Proto = R->castAs<FunctionProtoType>();
11245  // Make sure we don't have any parameters.
11247  unsigned NumParam = Proto->getNumParams();
11248 
11249  // [C++2b]
11250  // A conversion function shall have no non-object parameters.
11251  if (NumParam == 1) {
11253  if (const auto *First =
11254  dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param);
11255  First && First->isExplicitObjectParameter())
11256  NumParam--;
11257  }
11258 
11259  if (NumParam != 0) {
11260  Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
11261  // Delete the parameters.
11262  FTI.freeParams();
11263  D.setInvalidType();
11264  } else if (Proto->isVariadic()) {
11265  Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
11266  D.setInvalidType();
11267  }
11268 
11269  // Diagnose "&operator bool()" and other such nonsense. This
11270  // is actually a gcc extension which we don't support.
11271  if (Proto->getReturnType() != ConvType) {
11272  bool NeedsTypedef = false;
11273  SourceRange Before, After;
11274 
11275  // Walk the chunks and extract information on them for our diagnostic.
11276  bool PastFunctionChunk = false;
11277  for (auto &Chunk : D.type_objects()) {
11278  switch (Chunk.Kind) {
11280  if (!PastFunctionChunk) {
11281  if (Chunk.Fun.HasTrailingReturnType) {
11282  TypeSourceInfo *TRT = nullptr;
11283  GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
11284  if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
11285  }
11286  PastFunctionChunk = true;
11287  break;
11288  }
11289  [[fallthrough]];
11291  NeedsTypedef = true;
11292  extendRight(After, Chunk.getSourceRange());
11293  break;
11294 
11299  case DeclaratorChunk::Pipe:
11300  extendLeft(Before, Chunk.getSourceRange());
11301  break;
11302 
11304  extendLeft(Before, Chunk.Loc);
11305  extendRight(After, Chunk.EndLoc);
11306  break;
11307  }
11308  }
11309 
11310  SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11311  After.isValid() ? After.getBegin() :
11312  D.getIdentifierLoc();
11313  auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
11314  DB << Before << After;
11315 
11316  if (!NeedsTypedef) {
11317  DB << /*don't need a typedef*/0;
11318 
11319  // If we can provide a correct fix-it hint, do so.
11320  if (After.isInvalid() && ConvTSI) {
11321  SourceLocation InsertLoc =
11323  DB << FixItHint::CreateInsertion(InsertLoc, " ")
11325  InsertLoc, CharSourceRange::getTokenRange(Before))
11326  << FixItHint::CreateRemoval(Before);
11327  }
11328  } else if (!Proto->getReturnType()->isDependentType()) {
11329  DB << /*typedef*/1 << Proto->getReturnType();
11330  } else if (getLangOpts().CPlusPlus11) {
11331  DB << /*alias template*/2 << Proto->getReturnType();
11332  } else {
11333  DB << /*might not be fixable*/3;
11334  }
11335 
11336  // Recover by incorporating the other type chunks into the result type.
11337  // Note, this does *not* change the name of the function. This is compatible
11338  // with the GCC extension:
11339  // struct S { &operator int(); } s;
11340  // int &r = s.operator int(); // ok in GCC
11341  // S::operator int&() {} // error in GCC, function name is 'operator int'.
11342  ConvType = Proto->getReturnType();
11343  }
11344 
11345  // C++ [class.conv.fct]p4:
11346  // The conversion-type-id shall not represent a function type nor
11347  // an array type.
11348  if (ConvType->isArrayType()) {
11349  Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
11350  ConvType = Context.getPointerType(ConvType);
11351  D.setInvalidType();
11352  } else if (ConvType->isFunctionType()) {
11353  Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
11354  ConvType = Context.getPointerType(ConvType);
11355  D.setInvalidType();
11356  }
11357 
11358  // Rebuild the function type "R" without any parameters (in case any
11359  // of the errors above fired) and with the conversion type as the
11360  // return type.
11361  if (D.isInvalidType())
11362  R = Context.getFunctionType(ConvType, std::nullopt,
11363  Proto->getExtProtoInfo());
11364 
11365  // C++0x explicit conversion operators.
11367  Diag(DS.getExplicitSpecLoc(),
11369  ? diag::warn_cxx98_compat_explicit_conversion_functions
11370  : diag::ext_explicit_conversion_functions)
11372 }
11373 
11374 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
11375 /// the declaration of the given C++ conversion function. This routine
11376 /// is responsible for recording the conversion function in the C++
11377 /// class, if possible.
11379  assert(Conversion && "Expected to receive a conversion function declaration");
11380 
11381  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
11382 
11383  // Make sure we aren't redeclaring the conversion function.
11384  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
11385  // C++ [class.conv.fct]p1:
11386  // [...] A conversion function is never used to convert a
11387  // (possibly cv-qualified) object to the (possibly cv-qualified)
11388  // same object type (or a reference to it), to a (possibly
11389  // cv-qualified) base class of that type (or a reference to it),
11390  // or to (possibly cv-qualified) void.
11391  QualType ClassType
11393  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11394  ConvType = ConvTypeRef->getPointeeType();
11395  if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11397  /* Suppress diagnostics for instantiations. */;
11398  else if (Conversion->size_overridden_methods() != 0)
11399  /* Suppress diagnostics for overriding virtual function in a base class. */;
11400  else if (ConvType->isRecordType()) {
11401  ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
11402  if (ConvType == ClassType)
11403  Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
11404  << ClassType;
11405  else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
11406  Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
11407  << ClassType << ConvType;
11408  } else if (ConvType->isVoidType()) {
11409  Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
11410  << ClassType << ConvType;
11411  }
11412 
11413  if (FunctionTemplateDecl *ConversionTemplate =
11414  Conversion->getDescribedFunctionTemplate()) {
11415  if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11416  ConvType = ConvTypePtr->getPointeeType();
11417  }
11418  if (ConvType->isUndeducedAutoType()) {
11419  Diag(Conversion->getTypeSpecStartLoc(), diag::err_auto_not_allowed)
11420  << getReturnTypeLoc(Conversion).getSourceRange()
11421  << llvm::to_underlying(ConvType->castAs<AutoType>()->getKeyword())
11422  << /* in declaration of conversion function template= */ 24;
11423  }
11424 
11425  return ConversionTemplate;
11426  }
11427 
11428  return Conversion;
11429 }
11430 
11432  DeclarationName Name, QualType R) {
11433  CheckExplicitObjectMemberFunction(D, Name, R, false, DC);
11434 }
11435 
11437  CheckExplicitObjectMemberFunction(D, {}, {}, true);
11438 }
11439 
11441  DeclarationName Name, QualType R,
11442  bool IsLambda, DeclContext *DC) {
11443  if (!D.isFunctionDeclarator())
11444  return;
11445 
11447  if (FTI.NumParams == 0)
11448  return;
11449  ParmVarDecl *ExplicitObjectParam = nullptr;
11450  for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11451  const auto &ParamInfo = FTI.Params[Idx];
11452  if (!ParamInfo.Param)
11453  continue;
11454  ParmVarDecl *Param = cast<ParmVarDecl>(ParamInfo.Param);
11455  if (!Param->isExplicitObjectParameter())
11456  continue;
11457  if (Idx == 0) {
11458  ExplicitObjectParam = Param;
11459  continue;
11460  } else {
11461  Diag(Param->getLocation(),
11462  diag::err_explicit_object_parameter_must_be_first)
11463  << IsLambda << Param->getSourceRange();
11464  }
11465  }
11466  if (!ExplicitObjectParam)
11467  return;
11468 
11469  if (ExplicitObjectParam->hasDefaultArg()) {
11470  Diag(ExplicitObjectParam->getLocation(),
11471  diag::err_explicit_object_default_arg)
11472  << ExplicitObjectParam->getSourceRange();
11473  }
11474 
11477  D.isStaticMember())) {
11478  Diag(ExplicitObjectParam->getBeginLoc(),
11479  diag::err_explicit_object_parameter_nonmember)
11480  << D.getSourceRange() << /*static=*/0 << IsLambda;
11481  D.setInvalidType();
11482  }
11483 
11484  if (D.getDeclSpec().isVirtualSpecified()) {
11485  Diag(ExplicitObjectParam->getBeginLoc(),
11486  diag::err_explicit_object_parameter_nonmember)
11487  << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11488  D.setInvalidType();
11489  }
11490 
11491  if (IsLambda && FTI.hasMutableQualifier()) {
11492  Diag(ExplicitObjectParam->getBeginLoc(),
11493  diag::err_explicit_object_parameter_mutable)
11494  << D.getSourceRange();
11495  }
11496 
11497  if (IsLambda)
11498  return;
11499 
11500  if (!DC || !DC->isRecord()) {
11501  Diag(ExplicitObjectParam->getLocation(),
11502  diag::err_explicit_object_parameter_nonmember)
11503  << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11504  D.setInvalidType();
11505  return;
11506  }
11507 
11508  // CWG2674: constructors and destructors cannot have explicit parameters.
11509  if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
11510  Name.getNameKind() == DeclarationName::CXXDestructorName) {
11511  Diag(ExplicitObjectParam->getBeginLoc(),
11512  diag::err_explicit_object_parameter_constructor)
11513  << (Name.getNameKind() == DeclarationName::CXXDestructorName)
11514  << D.getSourceRange();
11515  D.setInvalidType();
11516  }
11517 }
11518 
11519 namespace {
11520 /// Utility class to accumulate and print a diagnostic listing the invalid
11521 /// specifier(s) on a declaration.
11522 struct BadSpecifierDiagnoser {
11523  BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11524  : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11525  ~BadSpecifierDiagnoser() {
11526  Diagnostic << Specifiers;
11527  }
11528 
11529  template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11530  return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11531  }
11532  void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11533  return check(SpecLoc,
11535  }
11536  void check(SourceLocation SpecLoc, const char *Spec) {
11537  if (SpecLoc.isInvalid()) return;
11538  Diagnostic << SourceRange(SpecLoc, SpecLoc);
11539  if (!Specifiers.empty()) Specifiers += " ";
11540  Specifiers += Spec;
11541  }
11542 
11543  Sema &S;
11544  Sema::SemaDiagnosticBuilder Diagnostic;
11545  std::string Specifiers;
11546 };
11547 }
11548 
11549 /// Check the validity of a declarator that we parsed for a deduction-guide.
11550 /// These aren't actually declarators in the grammar, so we need to check that
11551 /// the user didn't specify any pieces that are not part of the deduction-guide
11552 /// grammar. Return true on invalid deduction-guide.
11554  StorageClass &SC) {
11555  TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11556  TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11557  assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11558 
11559  // C++ [temp.deduct.guide]p3:
11560  // A deduction-gide shall be declared in the same scope as the
11561  // corresponding class template.
11563  GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11564  Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
11565  << GuidedTemplateDecl;
11566  NoteTemplateLocation(*GuidedTemplateDecl);
11567  }
11568 
11569  auto &DS = D.getMutableDeclSpec();
11570  // We leave 'friend' and 'virtual' to be rejected in the normal way.
11571  if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11572  DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11573  DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11574  BadSpecifierDiagnoser Diagnoser(
11575  *this, D.getIdentifierLoc(),
11576  diag::err_deduction_guide_invalid_specifier);
11577 
11578  Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
11579  DS.ClearStorageClassSpecs();
11580  SC = SC_None;
11581 
11582  // 'explicit' is permitted.
11583  Diagnoser.check(DS.getInlineSpecLoc(), "inline");
11584  Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
11585  Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
11586  DS.ClearConstexprSpec();
11587 
11588  Diagnoser.check(DS.getConstSpecLoc(), "const");
11589  Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11590  Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11591  Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11592  Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11593  DS.ClearTypeQualifiers();
11594 
11595  Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11596  Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11597  Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11598  Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11599  DS.ClearTypeSpecType();
11600  }
11601 
11602  if (D.isInvalidType())
11603  return true;
11604 
11605  // Check the declarator is simple enough.
11606  bool FoundFunction = false;
11607  for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11608  if (Chunk.Kind == DeclaratorChunk::Paren)
11609  continue;
11610  if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11612  diag::err_deduction_guide_with_complex_decl)
11613  << D.getSourceRange();
11614  break;
11615  }
11616  if (!Chunk.Fun.hasTrailingReturnType())
11617  return Diag(D.getName().getBeginLoc(),
11618  diag::err_deduction_guide_no_trailing_return_type);
11619 
11620  // Check that the return type is written as a specialization of
11621  // the template specified as the deduction-guide's name.
11622  // The template name may not be qualified. [temp.deduct.guide]
11623  ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11624  TypeSourceInfo *TSI = nullptr;
11625  QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11626  assert(TSI && "deduction guide has valid type but invalid return type?");
11627  bool AcceptableReturnType = false;
11628  bool MightInstantiateToSpecialization = false;
11629  if (auto RetTST =
11631  TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11632  bool TemplateMatches =
11633  Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
11634  auto TKind = SpecifiedName.getKind();
11635  // A Using TemplateName can't actually be valid (either it's qualified, or
11636  // we're in the wrong scope). But we have diagnosed these problems
11637  // already.
11638  bool SimplyWritten = TKind == TemplateName::Template ||
11639  TKind == TemplateName::UsingTemplate;
11640  if (SimplyWritten && TemplateMatches)
11641  AcceptableReturnType = true;
11642  else {
11643  // This could still instantiate to the right type, unless we know it
11644  // names the wrong class template.
11645  auto *TD = SpecifiedName.getAsTemplateDecl();
11646  MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
11647  !TemplateMatches);
11648  }
11649  } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11650  MightInstantiateToSpecialization = true;
11651  }
11652 
11653  if (!AcceptableReturnType)
11654  return Diag(TSI->getTypeLoc().getBeginLoc(),
11655  diag::err_deduction_guide_bad_trailing_return_type)
11656  << GuidedTemplate << TSI->getType()
11657  << MightInstantiateToSpecialization
11658  << TSI->getTypeLoc().getSourceRange();
11659 
11660  // Keep going to check that we don't have any inner declarator pieces (we
11661  // could still have a function returning a pointer to a function).
11662  FoundFunction = true;
11663  }
11664 
11665  if (D.isFunctionDefinition())
11666  // we can still create a valid deduction guide here.
11667  Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11668  return false;
11669 }
11670 
11671 //===----------------------------------------------------------------------===//
11672 // Namespace Handling
11673 //===----------------------------------------------------------------------===//
11674 
11675 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11676 /// reopened.
11678  SourceLocation Loc,
11679  IdentifierInfo *II, bool *IsInline,
11680  NamespaceDecl *PrevNS) {
11681  assert(*IsInline != PrevNS->isInline());
11682 
11683  // 'inline' must appear on the original definition, but not necessarily
11684  // on all extension definitions, so the note should point to the first
11685  // definition to avoid confusion.
11686  PrevNS = PrevNS->getFirstDecl();
11687 
11688  if (PrevNS->isInline())
11689  // The user probably just forgot the 'inline', so suggest that it
11690  // be added back.
11691  S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11692  << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11693  else
11694  S.Diag(Loc, diag::err_inline_namespace_mismatch);
11695 
11696  S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11697  *IsInline = PrevNS->isInline();
11698 }
11699 
11700 /// ActOnStartNamespaceDef - This is called at the start of a namespace
11701 /// definition.
11703  SourceLocation InlineLoc,
11704  SourceLocation NamespaceLoc,
11705  SourceLocation IdentLoc, IdentifierInfo *II,
11706  SourceLocation LBrace,
11707  const ParsedAttributesView &AttrList,
11708  UsingDirectiveDecl *&UD, bool IsNested) {
11709  SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11710  // For anonymous namespace, take the location of the left brace.
11711  SourceLocation Loc = II ? IdentLoc : LBrace;
11712  bool IsInline = InlineLoc.isValid();
11713  bool IsInvalid = false;
11714  bool IsStd = false;
11715  bool AddToKnown = false;
11716  Scope *DeclRegionScope = NamespcScope->getParent();
11717 
11718  NamespaceDecl *PrevNS = nullptr;
11719  if (II) {
11720  // C++ [namespace.std]p7:
11721  // A translation unit shall not declare namespace std to be an inline
11722  // namespace (9.8.2).
11723  //
11724  // Precondition: the std namespace is in the file scope and is declared to
11725  // be inline
11726  auto DiagnoseInlineStdNS = [&]() {
11727  assert(IsInline && II->isStr("std") &&
11729  "Precondition of DiagnoseInlineStdNS not met");
11730  Diag(InlineLoc, diag::err_inline_namespace_std)
11731  << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6));
11732  IsInline = false;
11733  };
11734  // C++ [namespace.def]p2:
11735  // The identifier in an original-namespace-definition shall not
11736  // have been previously defined in the declarative region in
11737  // which the original-namespace-definition appears. The
11738  // identifier in an original-namespace-definition is the name of
11739  // the namespace. Subsequently in that declarative region, it is
11740  // treated as an original-namespace-name.
11741  //
11742  // Since namespace names are unique in their scope, and we don't
11743  // look through using directives, just look for any ordinary names
11744  // as if by qualified name lookup.
11745  LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11748  NamedDecl *PrevDecl =
11749  R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11750  PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11751 
11752  if (PrevNS) {
11753  // This is an extended namespace definition.
11754  if (IsInline && II->isStr("std") &&
11756  DiagnoseInlineStdNS();
11757  else if (IsInline != PrevNS->isInline())
11758  DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11759  &IsInline, PrevNS);
11760  } else if (PrevDecl) {
11761  // This is an invalid name redefinition.
11762  Diag(Loc, diag::err_redefinition_different_kind)
11763  << II;
11764  Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11765  IsInvalid = true;
11766  // Continue on to push Namespc as current DeclContext and return it.
11767  } else if (II->isStr("std") &&
11769  if (IsInline)
11770  DiagnoseInlineStdNS();
11771  // This is the first "real" definition of the namespace "std", so update
11772  // our cache of the "std" namespace to point at this definition.
11773  PrevNS = getStdNamespace();
11774  IsStd = true;
11775  AddToKnown = !IsInline;
11776  } else {
11777  // We've seen this namespace for the first time.
11778  AddToKnown = !IsInline;
11779  }
11780  } else {
11781  // Anonymous namespaces.
11782 
11783  // Determine whether the parent already has an anonymous namespace.
11785  if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11786  PrevNS = TU->getAnonymousNamespace();
11787  } else {
11788  NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11789  PrevNS = ND->getAnonymousNamespace();
11790  }
11791 
11792  if (PrevNS && IsInline != PrevNS->isInline())
11793  DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11794  &IsInline, PrevNS);
11795  }
11796 
11798  Context, CurContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);
11799  if (IsInvalid)
11800  Namespc->setInvalidDecl();
11801 
11802  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11803  AddPragmaAttributes(DeclRegionScope, Namespc);
11804  ProcessAPINotes(Namespc);
11805 
11806  // FIXME: Should we be merging attributes?
11807  if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11809 
11810  if (IsStd)
11811  StdNamespace = Namespc;
11812  if (AddToKnown)
11813  KnownNamespaces[Namespc] = false;
11814 
11815  if (II) {
11816  PushOnScopeChains(Namespc, DeclRegionScope);
11817  } else {
11818  // Link the anonymous namespace into its parent.
11820  if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11821  TU->setAnonymousNamespace(Namespc);
11822  } else {
11823  cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11824  }
11825 
11826  CurContext->addDecl(Namespc);
11827 
11828  // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
11829  // behaves as if it were replaced by
11830  // namespace unique { /* empty body */ }
11831  // using namespace unique;
11832  // namespace unique { namespace-body }
11833  // where all occurrences of 'unique' in a translation unit are
11834  // replaced by the same identifier and this identifier differs
11835  // from all other identifiers in the entire program.
11836 
11837  // We just create the namespace with an empty name and then add an
11838  // implicit using declaration, just like the standard suggests.
11839  //
11840  // CodeGen enforces the "universally unique" aspect by giving all
11841  // declarations semantically contained within an anonymous
11842  // namespace internal linkage.
11843 
11844  if (!PrevNS) {
11846  /* 'using' */ LBrace,
11847  /* 'namespace' */ SourceLocation(),
11848  /* qualifier */ NestedNameSpecifierLoc(),
11849  /* identifier */ SourceLocation(),
11850  Namespc,
11851  /* Ancestor */ Parent);
11852  UD->setImplicit();
11853  Parent->addDecl(UD);
11854  }
11855  }
11856 
11857  ActOnDocumentableDecl(Namespc);
11858 
11859  // Although we could have an invalid decl (i.e. the namespace name is a
11860  // redefinition), push it as current DeclContext and try to continue parsing.
11861  // FIXME: We should be able to push Namespc here, so that the each DeclContext
11862  // for the namespace has the declarations that showed up in that particular
11863  // namespace definition.
11864  PushDeclContext(NamespcScope, Namespc);
11865  return Namespc;
11866 }
11867 
11868 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11869 /// is a namespace alias, returns the namespace it points to.
11871  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11872  return AD->getNamespace();
11873  return dyn_cast_or_null<NamespaceDecl>(D);
11874 }
11875 
11876 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
11877 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
11879  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11880  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11881  Namespc->setRBraceLoc(RBrace);
11882  PopDeclContext();
11883  if (Namespc->hasAttr<VisibilityAttr>())
11884  PopPragmaVisibility(true, RBrace);
11885  // If this namespace contains an export-declaration, export it now.
11886  if (DeferredExportedNamespaces.erase(Namespc))
11888 }
11889 
11891  return cast_or_null<CXXRecordDecl>(
11893 }
11894 
11896  return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11897 }
11898 
11900  return cast_or_null<NamespaceDecl>(
11902 }
11903 namespace {
11904 
11905 enum UnsupportedSTLSelect {
11906  USS_InvalidMember,
11907  USS_MissingMember,
11908  USS_NonTrivial,
11909  USS_Other
11910 };
11911 
11912 struct InvalidSTLDiagnoser {
11913  Sema &S;
11914  SourceLocation Loc;
11915  QualType TyForDiags;
11916 
11917  QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11918  const VarDecl *VD = nullptr) {
11919  {
11920  auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11921  << TyForDiags << ((int)Sel);
11922  if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11923  assert(!Name.empty());
11924  D << Name;
11925  }
11926  }
11927  if (Sel == USS_InvalidMember) {
11928  S.Diag(VD->getLocation(), diag::note_var_declared_here)
11929  << VD << VD->getSourceRange();
11930  }
11931  return QualType();
11932  }
11933 };
11934 } // namespace
11935 
11937  SourceLocation Loc,
11938  ComparisonCategoryUsage Usage) {
11939  assert(getLangOpts().CPlusPlus &&
11940  "Looking for comparison category type outside of C++.");
11941 
11942  // Use an elaborated type for diagnostics which has a name containing the
11943  // prepended 'std' namespace but not any inline namespace names.
11944  auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11945  auto *NNS =
11948  Info->getType());
11949  };
11950 
11951  // Check if we've already successfully checked the comparison category type
11952  // before. If so, skip checking it again.
11954  if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11955  // The only thing we need to check is that the type has a reachable
11956  // definition in the current context.
11957  if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11958  return QualType();
11959 
11960  return Info->getType();
11961  }
11962 
11963  // If lookup failed
11964  if (!Info) {
11965  std::string NameForDiags = "std::";
11967  Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11968  << NameForDiags << (int)Usage;
11969  return QualType();
11970  }
11971 
11972  assert(Info->Kind == Kind);
11973  assert(Info->Record);
11974 
11975  // Update the Record decl in case we encountered a forward declaration on our
11976  // first pass. FIXME: This is a bit of a hack.
11977  if (Info->Record->hasDefinition())
11978  Info->Record = Info->Record->getDefinition();
11979 
11980  if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11981  return QualType();
11982 
11983  InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11984 
11985  if (!Info->Record->isTriviallyCopyable())
11986  return UnsupportedSTLError(USS_NonTrivial);
11987 
11988  for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11989  CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11990  // Tolerate empty base classes.
11991  if (Base->isEmpty())
11992  continue;
11993  // Reject STL implementations which have at least one non-empty base.
11994  return UnsupportedSTLError();
11995  }
11996 
11997  // Check that the STL has implemented the types using a single integer field.
11998  // This expectation allows better codegen for builtin operators. We require:
11999  // (1) The class has exactly one field.
12000  // (2) The field is an integral or enumeration type.
12001  auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
12002  if (std::distance(FIt, FEnd) != 1 ||
12003  !FIt->getType()->isIntegralOrEnumerationType()) {
12004  return UnsupportedSTLError();
12005  }
12006 
12007  // Build each of the require values and store them in Info.
12008  for (ComparisonCategoryResult CCR :
12010  StringRef MemName = ComparisonCategories::getResultString(CCR);
12011  ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
12012 
12013  if (!ValInfo)
12014  return UnsupportedSTLError(USS_MissingMember, MemName);
12015 
12016  VarDecl *VD = ValInfo->VD;
12017  assert(VD && "should not be null!");
12018 
12019  // Attempt to diagnose reasons why the STL definition of this type
12020  // might be foobar, including it failing to be a constant expression.
12021  // TODO Handle more ways the lookup or result can be invalid.
12022  if (!VD->isStaticDataMember() ||
12024  return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
12025 
12026  // Attempt to evaluate the var decl as a constant expression and extract
12027  // the value of its first field as a ICE. If this fails, the STL
12028  // implementation is not supported.
12029  if (!ValInfo->hasValidIntValue())
12030  return UnsupportedSTLError();
12031 
12032  MarkVariableReferenced(Loc, VD);
12033  }
12034 
12035  // We've successfully built the required types and expressions. Update
12036  // the cache and return the newly cached value.
12037  FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
12038  return Info->getType();
12039 }
12040 
12041 /// Retrieve the special "std" namespace, which may require us to
12042 /// implicitly define the namespace.
12044  if (!StdNamespace) {
12045  // The "std" namespace has not yet been defined, so build one implicitly.
12048  /*Inline=*/false, SourceLocation(), SourceLocation(),
12049  &PP.getIdentifierTable().get("std"),
12050  /*PrevDecl=*/nullptr, /*Nested=*/false);
12051  getStdNamespace()->setImplicit(true);
12052  // We want the created NamespaceDecl to be available for redeclaration
12053  // lookups, but not for regular name lookups.
12056  }
12057 
12058  return getStdNamespace();
12059 }
12060 
12062  assert(getLangOpts().CPlusPlus &&
12063  "Looking for std::initializer_list outside of C++.");
12064 
12065  // We're looking for implicit instantiations of
12066  // template <typename E> class std::initializer_list.
12067 
12068  if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
12069  return false;
12070 
12071  ClassTemplateDecl *Template = nullptr;
12072  const TemplateArgument *Arguments = nullptr;
12073 
12074  if (const RecordType *RT = Ty->getAs<RecordType>()) {
12075 
12077  dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
12078  if (!Specialization)
12079  return false;
12080 
12081  Template = Specialization->getSpecializedTemplate();
12082  Arguments = Specialization->getTemplateArgs().data();
12083  } else if (const TemplateSpecializationType *TST =
12085  Template = dyn_cast_or_null<ClassTemplateDecl>(
12086  TST->getTemplateName().getAsTemplateDecl());
12087  Arguments = TST->template_arguments().begin();
12088  }
12089  if (!Template)
12090  return false;
12091 
12092  if (!StdInitializerList) {
12093  // Haven't recognized std::initializer_list yet, maybe this is it.
12094  CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
12095  if (TemplateClass->getIdentifier() !=
12096  &PP.getIdentifierTable().get("initializer_list") ||
12097  !getStdNamespace()->InEnclosingNamespaceSetOf(
12098  TemplateClass->getDeclContext()))
12099  return false;
12100  // This is a template called std::initializer_list, but is it the right
12101  // template?
12102  TemplateParameterList *Params = Template->getTemplateParameters();
12103  if (Params->getMinRequiredArguments() != 1)
12104  return false;
12105  if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
12106  return false;
12107 
12108  // It's the right template.
12109  StdInitializerList = Template;
12110  }
12111 
12113  return false;
12114 
12115  // This is an instance of std::initializer_list. Find the argument type.
12116  if (Element)
12117  *Element = Arguments[0].getAsType();
12118  return true;
12119 }
12120 
12123  if (!Std) {
12124  S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
12125  return nullptr;
12126  }
12127 
12128  LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
12130  if (!S.LookupQualifiedName(Result, Std)) {
12131  S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
12132  return nullptr;
12133  }
12134  ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
12135  if (!Template) {
12136  Result.suppressDiagnostics();
12137  // We found something weird. Complain about the first thing we found.
12138  NamedDecl *Found = *Result.begin();
12139  S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
12140  return nullptr;
12141  }
12142 
12143  // We found some template called std::initializer_list. Now verify that it's
12144  // correct.
12145  TemplateParameterList *Params = Template->getTemplateParameters();
12146  if (Params->getMinRequiredArguments() != 1 ||
12147  !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
12148  S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
12149  return nullptr;
12150  }
12151 
12152  return Template;
12153 }
12154 
12156  if (!StdInitializerList) {
12158  if (!StdInitializerList)
12159  return QualType();
12160  }
12161 
12162  TemplateArgumentListInfo Args(Loc, Loc);
12165  Loc)));
12166  return Context.getElaboratedType(
12170 }
12171 
12173  // C++ [dcl.init.list]p2:
12174  // A constructor is an initializer-list constructor if its first parameter
12175  // is of type std::initializer_list<E> or reference to possibly cv-qualified
12176  // std::initializer_list<E> for some type E, and either there are no other
12177  // parameters or else all other parameters have default arguments.
12178  if (!Ctor->hasOneParamOrDefaultArgs())
12179  return false;
12180 
12181  QualType ArgType = Ctor->getParamDecl(0)->getType();
12182  if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12183  ArgType = RT->getPointeeType().getUnqualifiedType();
12184 
12185  return isStdInitializerList(ArgType, nullptr);
12186 }
12187 
12188 /// Determine whether a using statement is in a context where it will be
12189 /// apply in all contexts.
12191  switch (CurContext->getDeclKind()) {
12192  case Decl::TranslationUnit:
12193  return true;
12194  case Decl::LinkageSpec:
12196  default:
12197  return false;
12198  }
12199 }
12200 
12201 namespace {
12202 
12203 // Callback to only accept typo corrections that are namespaces.
12204 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12205 public:
12206  bool ValidateCandidate(const TypoCorrection &candidate) override {
12207  if (NamedDecl *ND = candidate.getCorrectionDecl())
12208  return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
12209  return false;
12210  }
12211 
12212  std::unique_ptr<CorrectionCandidateCallback> clone() override {
12213  return std::make_unique<NamespaceValidatorCCC>(*this);
12214  }
12215 };
12216 
12217 }
12218 
12219 static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12220  Sema &S) {
12221  auto *ND = cast<NamespaceDecl>(Corrected.getFoundDecl());
12222  Module *M = ND->getOwningModule();
12223  assert(M && "hidden namespace definition not in a module?");
12224 
12225  if (M->isExplicitGlobalModule())
12226  S.Diag(Corrected.getCorrectionRange().getBegin(),
12227  diag::err_module_unimported_use_header)
12229  << /*Header Name*/ false;
12230  else
12231  S.Diag(Corrected.getCorrectionRange().getBegin(),
12232  diag::err_module_unimported_use)
12233  << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12234  << M->getTopLevelModuleName();
12235 }
12236 
12238  CXXScopeSpec &SS,
12239  SourceLocation IdentLoc,
12240  IdentifierInfo *Ident) {
12241  R.clear();
12242  NamespaceValidatorCCC CCC{};
12243  if (TypoCorrection Corrected =
12244  S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
12246  // Generally we find it is confusing more than helpful to diagnose the
12247  // invisible namespace.
12248  // See https://github.com/llvm/llvm-project/issues/73893.
12249  //
12250  // However, we should diagnose when the users are trying to using an
12251  // invisible namespace. So we handle the case specially here.
12252  if (isa_and_nonnull<NamespaceDecl>(Corrected.getFoundDecl()) &&
12253  Corrected.requiresImport()) {
12254  DiagnoseInvisibleNamespace(Corrected, S);
12255  } else if (DeclContext *DC = S.computeDeclContext(SS, false)) {
12256  std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
12257  bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
12258  Ident->getName().equals(CorrectedStr);
12259  S.diagnoseTypo(Corrected,
12260  S.PDiag(diag::err_using_directive_member_suggest)
12261  << Ident << DC << DroppedSpecifier << SS.getRange(),
12262  S.PDiag(diag::note_namespace_defined_here));
12263  } else {
12264  S.diagnoseTypo(Corrected,
12265  S.PDiag(diag::err_using_directive_suggest) << Ident,
12266  S.PDiag(diag::note_namespace_defined_here));
12267  }
12268  R.addDecl(Corrected.getFoundDecl());
12269  return true;
12270  }
12271  return false;
12272 }
12273 
12275  SourceLocation NamespcLoc, CXXScopeSpec &SS,
12276  SourceLocation IdentLoc,
12277  IdentifierInfo *NamespcName,
12278  const ParsedAttributesView &AttrList) {
12279  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12280  assert(NamespcName && "Invalid NamespcName.");
12281  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12282 
12283  // Get the innermost enclosing declaration scope.
12284  S = S->getDeclParent();
12285 
12286  UsingDirectiveDecl *UDir = nullptr;
12287  NestedNameSpecifier *Qualifier = nullptr;
12288  if (SS.isSet())
12289  Qualifier = SS.getScopeRep();
12290 
12291  // Lookup namespace name.
12292  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12293  LookupParsedName(R, S, &SS);
12294  if (R.isAmbiguous())
12295  return nullptr;
12296 
12297  if (R.empty()) {
12298  R.clear();
12299  // Allow "using namespace std;" or "using namespace ::std;" even if
12300  // "std" hasn't been defined yet, for GCC compatibility.
12301  if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
12302  NamespcName->isStr("std")) {
12303  Diag(IdentLoc, diag::ext_using_undefined_std);
12305  R.resolveKind();
12306  }
12307  // Otherwise, attempt typo correction.
12308  else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
12309  }
12310 
12311  if (!R.empty()) {
12312  NamedDecl *Named = R.getRepresentativeDecl();
12314  assert(NS && "expected namespace decl");
12315 
12316  // The use of a nested name specifier may trigger deprecation warnings.
12317  DiagnoseUseOfDecl(Named, IdentLoc);
12318 
12319  // C++ [namespace.udir]p1:
12320  // A using-directive specifies that the names in the nominated
12321  // namespace can be used in the scope in which the
12322  // using-directive appears after the using-directive. During
12323  // unqualified name lookup (3.4.1), the names appear as if they
12324  // were declared in the nearest enclosing namespace which
12325  // contains both the using-directive and the nominated
12326  // namespace. [Note: in this context, "contains" means "contains
12327  // directly or indirectly". ]
12328 
12329  // Find enclosing context containing both using-directive and
12330  // nominated namespace.
12331  DeclContext *CommonAncestor = NS;
12332  while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
12333  CommonAncestor = CommonAncestor->getParent();
12334 
12335  UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
12337  IdentLoc, Named, CommonAncestor);
12338 
12341  Diag(IdentLoc, diag::warn_using_directive_in_header);
12342  }
12343 
12344  PushUsingDirective(S, UDir);
12345  } else {
12346  Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12347  }
12348 
12349  if (UDir) {
12350  ProcessDeclAttributeList(S, UDir, AttrList);
12351  ProcessAPINotes(UDir);
12352  }
12353 
12354  return UDir;
12355 }
12356 
12358  // If the scope has an associated entity and the using directive is at
12359  // namespace or translation unit scope, add the UsingDirectiveDecl into
12360  // its lookup structure so qualified name lookup can find it.
12361  DeclContext *Ctx = S->getEntity();
12362  if (Ctx && !Ctx->isFunctionOrMethod())
12363  Ctx->addDecl(UDir);
12364  else
12365  // Otherwise, it is at block scope. The using-directives will affect lookup
12366  // only to the end of the scope.
12367  S->PushUsingDirective(UDir);
12368 }
12369 
12371  SourceLocation UsingLoc,
12372  SourceLocation TypenameLoc, CXXScopeSpec &SS,
12373  UnqualifiedId &Name,
12374  SourceLocation EllipsisLoc,
12375  const ParsedAttributesView &AttrList) {
12376  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12377 
12378  if (SS.isEmpty()) {
12379  Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
12380  return nullptr;
12381  }
12382 
12383  switch (Name.getKind()) {
12389  break;
12390 
12393  // C++11 inheriting constructors.
12394  Diag(Name.getBeginLoc(),
12396  ? diag::warn_cxx98_compat_using_decl_constructor
12397  : diag::err_using_decl_constructor)
12398  << SS.getRange();
12399 
12400  if (getLangOpts().CPlusPlus11) break;
12401 
12402  return nullptr;
12403 
12405  Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
12406  return nullptr;
12407 
12409  Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
12410  << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
12411  return nullptr;
12412 
12414  llvm_unreachable("cannot parse qualified deduction guide name");
12415  }
12416 
12417  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12418  DeclarationName TargetName = TargetNameInfo.getName();
12419  if (!TargetName)
12420  return nullptr;
12421 
12422  // Warn about access declarations.
12423  if (UsingLoc.isInvalid()) {
12424  Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
12425  ? diag::err_access_decl
12426  : diag::warn_access_decl_deprecated)
12427  << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
12428  }
12429 
12430  if (EllipsisLoc.isInvalid()) {
12433  return nullptr;
12434  } else {
12436  !TargetNameInfo.containsUnexpandedParameterPack()) {
12437  Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
12438  << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12439  EllipsisLoc = SourceLocation();
12440  }
12441  }
12442 
12443  NamedDecl *UD =
12444  BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
12445  SS, TargetNameInfo, EllipsisLoc, AttrList,
12446  /*IsInstantiation*/ false,
12447  AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
12448  if (UD)
12449  PushOnScopeChains(UD, S, /*AddToContext*/ false);
12450 
12451  return UD;
12452 }
12453 
12455  SourceLocation UsingLoc,
12456  SourceLocation EnumLoc,
12457  SourceLocation IdentLoc,
12458  IdentifierInfo &II, CXXScopeSpec *SS) {
12459  assert(!SS->isInvalid() && "ScopeSpec is invalid");
12460  TypeSourceInfo *TSI = nullptr;
12461  QualType EnumTy = GetTypeFromParser(
12462  getTypeName(II, IdentLoc, S, SS, /*isClassName=*/false,
12463  /*HasTrailingDot=*/false,
12464  /*ObjectType=*/nullptr, /*IsCtorOrDtorName=*/false,
12465  /*WantNontrivialTypeSourceInfo=*/true),
12466  &TSI);
12467  if (EnumTy.isNull()) {
12468  Diag(IdentLoc, SS && isDependentScopeSpecifier(*SS)
12469  ? diag::err_using_enum_is_dependent
12470  : diag::err_unknown_typename)
12471  << II.getName()
12472  << SourceRange(SS ? SS->getBeginLoc() : IdentLoc, IdentLoc);
12473  return nullptr;
12474  }
12475 
12476  auto *Enum = dyn_cast_if_present<EnumDecl>(EnumTy->getAsTagDecl());
12477  if (!Enum) {
12478  Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
12479  return nullptr;
12480  }
12481 
12482  if (auto *Def = Enum->getDefinition())
12483  Enum = Def;
12484 
12485  if (TSI == nullptr)
12486  TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);
12487 
12488  auto *UD =
12489  BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);
12490 
12491  if (UD)
12492  PushOnScopeChains(UD, S, /*AddToContext*/ false);
12493 
12494  return UD;
12495 }
12496 
12497 /// Determine whether a using declaration considers the given
12498 /// declarations as "equivalent", e.g., if they are redeclarations of
12499 /// the same entity or are both typedefs of the same type.
12500 static bool
12502  if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12503  return true;
12504 
12505  if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
12506  if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
12507  return Context.hasSameType(TD1->getUnderlyingType(),
12508  TD2->getUnderlyingType());
12509 
12510  // Two using_if_exists using-declarations are equivalent if both are
12511  // unresolved.
12512  if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
12513  isa<UnresolvedUsingIfExistsDecl>(D2))
12514  return true;
12515 
12516  return false;
12517 }
12518 
12519 
12520 /// Determines whether to create a using shadow decl for a particular
12521 /// decl, given the set of decls existing prior to this using lookup.
12523  const LookupResult &Previous,
12524  UsingShadowDecl *&PrevShadow) {
12525  // Diagnose finding a decl which is not from a base class of the
12526  // current class. We do this now because there are cases where this
12527  // function will silently decide not to build a shadow decl, which
12528  // will pre-empt further diagnostics.
12529  //
12530  // We don't need to do this in C++11 because we do the check once on
12531  // the qualifier.
12532  //
12533  // FIXME: diagnose the following if we care enough:
12534  // struct A { int foo; };
12535  // struct B : A { using A::foo; };
12536  // template <class T> struct C : A {};
12537  // template <class T> struct D : C<T> { using B::foo; } // <---
12538  // This is invalid (during instantiation) in C++03 because B::foo
12539  // resolves to the using decl in B, which is not a base class of D<T>.
12540  // We can't diagnose it immediately because C<T> is an unknown
12541  // specialization. The UsingShadowDecl in D<T> then points directly
12542  // to A::foo, which will look well-formed when we instantiate.
12543  // The right solution is to not collapse the shadow-decl chain.
12545  if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
12546  DeclContext *OrigDC = Orig->getDeclContext();
12547 
12548  // Handle enums and anonymous structs.
12549  if (isa<EnumDecl>(OrigDC))
12550  OrigDC = OrigDC->getParent();
12551  CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
12552  while (OrigRec->isAnonymousStructOrUnion())
12553  OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
12554 
12555  if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
12556  if (OrigDC == CurContext) {
12557  Diag(Using->getLocation(),
12558  diag::err_using_decl_nested_name_specifier_is_current_class)
12559  << Using->getQualifierLoc().getSourceRange();
12560  Diag(Orig->getLocation(), diag::note_using_decl_target);
12561  Using->setInvalidDecl();
12562  return true;
12563  }
12564 
12565  Diag(Using->getQualifierLoc().getBeginLoc(),
12566  diag::err_using_decl_nested_name_specifier_is_not_base_class)
12567  << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
12568  << Using->getQualifierLoc().getSourceRange();
12569  Diag(Orig->getLocation(), diag::note_using_decl_target);
12570  Using->setInvalidDecl();
12571  return true;
12572  }
12573  }
12574 
12575  if (Previous.empty()) return false;
12576 
12577  NamedDecl *Target = Orig;
12578  if (isa<UsingShadowDecl>(Target))
12579  Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12580 
12581  // If the target happens to be one of the previous declarations, we
12582  // don't have a conflict.
12583  //
12584  // FIXME: but we might be increasing its access, in which case we
12585  // should redeclare it.
12586  NamedDecl *NonTag = nullptr, *Tag = nullptr;
12587  bool FoundEquivalentDecl = false;
12588  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
12589  I != E; ++I) {
12590  NamedDecl *D = (*I)->getUnderlyingDecl();
12591  // We can have UsingDecls in our Previous results because we use the same
12592  // LookupResult for checking whether the UsingDecl itself is a valid
12593  // redeclaration.
12594  if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
12595  continue;
12596 
12597  if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
12598  // C++ [class.mem]p19:
12599  // If T is the name of a class, then [every named member other than
12600  // a non-static data member] shall have a name different from T
12601  if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
12602  !isa<IndirectFieldDecl>(Target) &&
12603  !isa<UnresolvedUsingValueDecl>(Target) &&
12605  CurContext,
12606  DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
12607  return true;
12608  }
12609 
12611  if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
12612  PrevShadow = Shadow;
12613  FoundEquivalentDecl = true;
12615  // We don't conflict with an existing using shadow decl of an equivalent
12616  // declaration, but we're not a redeclaration of it.
12617  FoundEquivalentDecl = true;
12618  }
12619 
12620  if (isVisible(D))
12621  (isa<TagDecl>(D) ? Tag : NonTag) = D;
12622  }
12623 
12624  if (FoundEquivalentDecl)
12625  return false;
12626 
12627  // Always emit a diagnostic for a mismatch between an unresolved
12628  // using_if_exists and a resolved using declaration in either direction.
12629  if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
12630  (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
12631  if (!NonTag && !Tag)
12632  return false;
12633  Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12634  Diag(Target->getLocation(), diag::note_using_decl_target);
12635  Diag((NonTag ? NonTag : Tag)->getLocation(),
12636  diag::note_using_decl_conflict);
12637  BUD->setInvalidDecl();
12638  return true;
12639  }
12640 
12641  if (FunctionDecl *FD = Target->getAsFunction()) {
12642  NamedDecl *OldDecl = nullptr;
12643  switch (CheckOverload(nullptr, FD, Previous, OldDecl,
12644  /*IsForUsingDecl*/ true)) {
12645  case Ovl_Overload:
12646  return false;
12647 
12648  case Ovl_NonFunction:
12649  Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12650  break;
12651 
12652  // We found a decl with the exact signature.
12653  case Ovl_Match:
12654  // If we're in a record, we want to hide the target, so we
12655  // return true (without a diagnostic) to tell the caller not to
12656  // build a shadow decl.
12657  if (CurContext->isRecord())
12658  return true;
12659 
12660  // If we're not in a record, this is an error.
12661  Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12662  break;
12663  }
12664 
12665  Diag(Target->getLocation(), diag::note_using_decl_target);
12666  Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
12667  BUD->setInvalidDecl();
12668  return true;
12669  }
12670 
12671  // Target is not a function.
12672 
12673  if (isa<TagDecl>(Target)) {
12674  // No conflict between a tag and a non-tag.
12675  if (!Tag) return false;
12676 
12677  Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12678  Diag(Target->getLocation(), diag::note_using_decl_target);
12679  Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12680  BUD->setInvalidDecl();
12681  return true;
12682  }
12683 
12684  // No conflict between a tag and a non-tag.
12685  if (!NonTag) return false;
12686 
12687  Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12688  Diag(Target->getLocation(), diag::note_using_decl_target);
12689  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12690  BUD->setInvalidDecl();
12691  return true;
12692 }
12693 
12694 /// Determine whether a direct base class is a virtual base class.
12696  if (!Derived->getNumVBases())
12697  return false;
12698  for (auto &B : Derived->bases())
12699  if (B.getType()->getAsCXXRecordDecl() == Base)
12700  return B.isVirtual();
12701  llvm_unreachable("not a direct base class");
12702 }
12703 
12704 /// Builds a shadow declaration corresponding to a 'using' declaration.
12706  NamedDecl *Orig,
12707  UsingShadowDecl *PrevDecl) {
12708  // If we resolved to another shadow declaration, just coalesce them.
12709  NamedDecl *Target = Orig;
12710  if (isa<UsingShadowDecl>(Target)) {
12711  Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12712  assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12713  }
12714 
12715  NamedDecl *NonTemplateTarget = Target;
12716  if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
12717  NonTemplateTarget = TargetTD->getTemplatedDecl();
12718 
12719  UsingShadowDecl *Shadow;
12720  if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12721  UsingDecl *Using = cast<UsingDecl>(BUD);
12722  bool IsVirtualBase =
12723  isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
12724  Using->getQualifier()->getAsRecordDecl());
12726  Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
12727  } else {
12729  Target->getDeclName(), BUD, Target);
12730  }
12731  BUD->addShadowDecl(Shadow);
12732 
12733  Shadow->setAccess(BUD->getAccess());
12734  if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12735  Shadow->setInvalidDecl();
12736 
12737  Shadow->setPreviousDecl(PrevDecl);
12738 
12739  if (S)
12740  PushOnScopeChains(Shadow, S);
12741  else
12742  CurContext->addDecl(Shadow);
12743 
12744 
12745  return Shadow;
12746 }
12747 
12748 /// Hides a using shadow declaration. This is required by the current
12749 /// using-decl implementation when a resolvable using declaration in a
12750 /// class is followed by a declaration which would hide or override
12751 /// one or more of the using decl's targets; for example:
12752 ///
12753 /// struct Base { void foo(int); };
12754 /// struct Derived : Base {
12755 /// using Base::foo;
12756 /// void foo(int);
12757 /// };
12758 ///
12759 /// The governing language is C++03 [namespace.udecl]p12:
12760 ///
12761 /// When a using-declaration brings names from a base class into a
12762 /// derived class scope, member functions in the derived class
12763 /// override and/or hide member functions with the same name and
12764 /// parameter types in a base class (rather than conflicting).
12765 ///
12766 /// There are two ways to implement this:
12767 /// (1) optimistically create shadow decls when they're not hidden
12768 /// by existing declarations, or
12769 /// (2) don't create any shadow decls (or at least don't make them
12770 /// visible) until we've fully parsed/instantiated the class.
12771 /// The problem with (1) is that we might have to retroactively remove
12772 /// a shadow decl, which requires several O(n) operations because the
12773 /// decl structures are (very reasonably) not designed for removal.
12774 /// (2) avoids this but is very fiddly and phase-dependent.
12776  if (Shadow->getDeclName().getNameKind() ==
12778  cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12779 
12780  // Remove it from the DeclContext...
12781  Shadow->getDeclContext()->removeDecl(Shadow);
12782 
12783  // ...and the scope, if applicable...
12784  if (S) {
12785  S->RemoveDecl(Shadow);
12786  IdResolver.RemoveDecl(Shadow);
12787  }
12788 
12789  // ...and the using decl.
12790  Shadow->getIntroducer()->removeShadowDecl(Shadow);
12791 
12792  // TODO: complain somehow if Shadow was used. It shouldn't
12793  // be possible for this to happen, because...?
12794 }
12795 
12796 /// Find the base specifier for a base class with the given type.
12798  QualType DesiredBase,
12799  bool &AnyDependentBases) {
12800  // Check whether the named type is a direct base class.
12801  CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12802  .getUnqualifiedType();
12803  for (auto &Base : Derived->bases()) {
12804  CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12805  if (CanonicalDesiredBase == BaseType)
12806  return &Base;
12807  if (BaseType->isDependentType())
12808  AnyDependentBases = true;
12809  }
12810  return nullptr;
12811 }
12812 
12813 namespace {
12814 class UsingValidatorCCC final : public CorrectionCandidateCallback {
12815 public:
12816  UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12817  NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12818  : HasTypenameKeyword(HasTypenameKeyword),
12819  IsInstantiation(IsInstantiation), OldNNS(NNS),
12820  RequireMemberOf(RequireMemberOf) {}
12821 
12822  bool ValidateCandidate(const TypoCorrection &Candidate) override {
12823  NamedDecl *ND = Candidate.getCorrectionDecl();
12824 
12825  // Keywords are not valid here.
12826  if (!ND || isa<NamespaceDecl>(ND))
12827  return false;
12828 
12829  // Completely unqualified names are invalid for a 'using' declaration.
12830  if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12831  return false;
12832 
12833  // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12834  // reject.
12835 
12836  if (RequireMemberOf) {
12837  auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12838  if (FoundRecord && FoundRecord->isInjectedClassName()) {
12839  // No-one ever wants a using-declaration to name an injected-class-name
12840  // of a base class, unless they're declaring an inheriting constructor.
12841  ASTContext &Ctx = ND->getASTContext();
12842  if (!Ctx.getLangOpts().CPlusPlus11)
12843  return false;
12844  QualType FoundType = Ctx.getRecordType(FoundRecord);
12845 
12846  // Check that the injected-class-name is named as a member of its own
12847  // type; we don't want to suggest 'using Derived::Base;', since that
12848  // means something else.
12850  Candidate.WillReplaceSpecifier()
12851  ? Candidate.getCorrectionSpecifier()
12852  : OldNNS;
12853  if (!Specifier->getAsType() ||
12854  !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12855  return false;
12856 
12857  // Check that this inheriting constructor declaration actually names a
12858  // direct base class of the current class.
12859  bool AnyDependentBases = false;
12860  if (!findDirectBaseWithType(RequireMemberOf,
12861  Ctx.getRecordType(FoundRecord),
12862  AnyDependentBases) &&
12863  !AnyDependentBases)
12864  return false;
12865  } else {
12866  auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12867  if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12868  return false;
12869 
12870  // FIXME: Check that the base class member is accessible?
12871  }
12872  } else {
12873  auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12874  if (FoundRecord && FoundRecord->isInjectedClassName())
12875  return false;
12876  }
12877 
12878  if (isa<TypeDecl>(ND))
12879  return HasTypenameKeyword || !IsInstantiation;
12880 
12881  return !HasTypenameKeyword;
12882  }
12883 
12884  std::unique_ptr<CorrectionCandidateCallback> clone() override {
12885  return std::make_unique<UsingValidatorCCC>(*this);
12886  }
12887 
12888 private:
12889  bool HasTypenameKeyword;
12890  bool IsInstantiation;
12891  NestedNameSpecifier *OldNNS;
12892  CXXRecordDecl *RequireMemberOf;
12893 };
12894 } // end anonymous namespace
12895 
12896 /// Remove decls we can't actually see from a lookup being used to declare
12897 /// shadow using decls.
12898 ///
12899 /// \param S - The scope of the potential shadow decl
12900 /// \param Previous - The lookup of a potential shadow decl's name.
12902  // It is really dumb that we have to do this.
12903  LookupResult::Filter F = Previous.makeFilter();
12904  while (F.hasNext()) {
12905  NamedDecl *D = F.next();
12906  if (!isDeclInScope(D, CurContext, S))
12907  F.erase();
12908  // If we found a local extern declaration that's not ordinarily visible,
12909  // and this declaration is being added to a non-block scope, ignore it.
12910  // We're only checking for scope conflicts here, not also for violations
12911  // of the linkage rules.
12912  else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12914  F.erase();
12915  }
12916  F.done();
12917 }
12918 
12919 /// Builds a using declaration.
12920 ///
12921 /// \param IsInstantiation - Whether this call arises from an
12922 /// instantiation of an unresolved using declaration. We treat
12923 /// the lookup differently for these declarations.
12925  Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12926  bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12927  DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12928  const ParsedAttributesView &AttrList, bool IsInstantiation,
12929  bool IsUsingIfExists) {
12930  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12931  SourceLocation IdentLoc = NameInfo.getLoc();
12932  assert(IdentLoc.isValid() && "Invalid TargetName location.");
12933 
12934  // FIXME: We ignore attributes for now.
12935 
12936  // For an inheriting constructor declaration, the name of the using
12937  // declaration is the name of a constructor in this class, not in the
12938  // base class.
12939  DeclarationNameInfo UsingName = NameInfo;
12941  if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12944 
12945  // Do the redeclaration lookup in the current scope.
12946  LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12948  Previous.setHideTags(false);
12949  if (S) {
12950  LookupName(Previous, S);
12951 
12953  } else {
12954  assert(IsInstantiation && "no scope in non-instantiation");
12955  if (CurContext->isRecord())
12957  else {
12958  // No redeclaration check is needed here; in non-member contexts we
12959  // diagnosed all possible conflicts with other using-declarations when
12960  // building the template:
12961  //
12962  // For a dependent non-type using declaration, the only valid case is
12963  // if we instantiate to a single enumerator. We check for conflicts
12964  // between shadow declarations we introduce, and we check in the template
12965  // definition for conflicts between a non-type using declaration and any
12966  // other declaration, which together covers all cases.
12967  //
12968  // A dependent typename using declaration will never successfully
12969  // instantiate, since it will always name a class member, so we reject
12970  // that in the template definition.
12971  }
12972  }
12973 
12974  // Check for invalid redeclarations.
12975  if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12976  SS, IdentLoc, Previous))
12977  return nullptr;
12978 
12979  // 'using_if_exists' doesn't make sense on an inherited constructor.
12980  if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12982  Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12983  return nullptr;
12984  }
12985 
12986  DeclContext *LookupContext = computeDeclContext(SS);
12988  if (!LookupContext || EllipsisLoc.isValid()) {
12989  NamedDecl *D;
12990  // Dependent scope, or an unexpanded pack
12991  if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
12992  SS, NameInfo, IdentLoc))
12993  return nullptr;
12994 
12995  if (HasTypenameKeyword) {
12996  // FIXME: not all declaration name kinds are legal here
12998  UsingLoc, TypenameLoc,
12999  QualifierLoc,
13000  IdentLoc, NameInfo.getName(),
13001  EllipsisLoc);
13002  } else {
13004  QualifierLoc, NameInfo, EllipsisLoc);
13005  }
13006  D->setAccess(AS);
13007  CurContext->addDecl(D);
13008  ProcessDeclAttributeList(S, D, AttrList);
13009  return D;
13010  }
13011 
13012  auto Build = [&](bool Invalid) {
13013  UsingDecl *UD =
13014  UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
13015  UsingName, HasTypenameKeyword);
13016  UD->setAccess(AS);
13017  CurContext->addDecl(UD);
13018  ProcessDeclAttributeList(S, UD, AttrList);
13019  UD->setInvalidDecl(Invalid);
13020  return UD;
13021  };
13022  auto BuildInvalid = [&]{ return Build(true); };
13023  auto BuildValid = [&]{ return Build(false); };
13024 
13025  if (RequireCompleteDeclContext(SS, LookupContext))
13026  return BuildInvalid();
13027 
13028  // Look up the target name.
13029  LookupResult R(*this, NameInfo, LookupOrdinaryName);
13030 
13031  // Unlike most lookups, we don't always want to hide tag
13032  // declarations: tag names are visible through the using declaration
13033  // even if hidden by ordinary names, *except* in a dependent context
13034  // where they may be used by two-phase lookup.
13035  if (!IsInstantiation)
13036  R.setHideTags(false);
13037 
13038  // For the purposes of this lookup, we have a base object type
13039  // equal to that of the current context.
13040  if (CurContext->isRecord()) {
13042  Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
13043  }
13044 
13045  LookupQualifiedName(R, LookupContext);
13046 
13047  // Validate the context, now we have a lookup
13048  if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
13049  IdentLoc, &R))
13050  return nullptr;
13051 
13052  if (R.empty() && IsUsingIfExists)
13054  UsingName.getName()),
13055  AS_public);
13056 
13057  // Try to correct typos if possible. If constructor name lookup finds no
13058  // results, that means the named class has no explicit constructors, and we
13059  // suppressed declaring implicit ones (probably because it's dependent or
13060  // invalid).
13061  if (R.empty() &&
13063  // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
13064  // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
13065  // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
13066  auto *II = NameInfo.getName().getAsIdentifierInfo();
13067  if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
13069  isa<TranslationUnitDecl>(LookupContext) &&
13070  getSourceManager().isInSystemHeader(UsingLoc))
13071  return nullptr;
13072  UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
13073  dyn_cast<CXXRecordDecl>(CurContext));
13074  if (TypoCorrection Corrected =
13075  CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
13076  CTK_ErrorRecovery)) {
13077  // We reject candidates where DroppedSpecifier == true, hence the
13078  // literal '0' below.
13079  diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
13080  << NameInfo.getName() << LookupContext << 0
13081  << SS.getRange());
13082 
13083  // If we picked a correction with no attached Decl we can't do anything
13084  // useful with it, bail out.
13085  NamedDecl *ND = Corrected.getCorrectionDecl();
13086  if (!ND)
13087  return BuildInvalid();
13088 
13089  // If we corrected to an inheriting constructor, handle it as one.
13090  auto *RD = dyn_cast<CXXRecordDecl>(ND);
13091  if (RD && RD->isInjectedClassName()) {
13092  // The parent of the injected class name is the class itself.
13093  RD = cast<CXXRecordDecl>(RD->getParent());
13094 
13095  // Fix up the information we'll use to build the using declaration.
13096  if (Corrected.WillReplaceSpecifier()) {
13098  Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
13099  QualifierLoc.getSourceRange());
13100  QualifierLoc = Builder.getWithLocInContext(Context);
13101  }
13102 
13103  // In this case, the name we introduce is the name of a derived class
13104  // constructor.
13105  auto *CurClass = cast<CXXRecordDecl>(CurContext);
13108  UsingName.setNamedTypeInfo(nullptr);
13109  for (auto *Ctor : LookupConstructors(RD))
13110  R.addDecl(Ctor);
13111  R.resolveKind();
13112  } else {
13113  // FIXME: Pick up all the declarations if we found an overloaded
13114  // function.
13115  UsingName.setName(ND->getDeclName());
13116  R.addDecl(ND);
13117  }
13118  } else {
13119  Diag(IdentLoc, diag::err_no_member)
13120  << NameInfo.getName() << LookupContext << SS.getRange();
13121  return BuildInvalid();
13122  }
13123  }
13124 
13125  if (R.isAmbiguous())
13126  return BuildInvalid();
13127 
13128  if (HasTypenameKeyword) {
13129  // If we asked for a typename and got a non-type decl, error out.
13130  if (!R.getAsSingle<TypeDecl>() &&
13132  Diag(IdentLoc, diag::err_using_typename_non_type);
13133  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13134  Diag((*I)->getUnderlyingDecl()->getLocation(),
13135  diag::note_using_decl_target);
13136  return BuildInvalid();
13137  }
13138  } else {
13139  // If we asked for a non-typename and we got a type, error out,
13140  // but only if this is an instantiation of an unresolved using
13141  // decl. Otherwise just silently find the type name.
13142  if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
13143  Diag(IdentLoc, diag::err_using_dependent_value_is_type);
13144  Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
13145  return BuildInvalid();
13146  }
13147  }
13148 
13149  // C++14 [namespace.udecl]p6:
13150  // A using-declaration shall not name a namespace.
13151  if (R.getAsSingle<NamespaceDecl>()) {
13152  Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
13153  << SS.getRange();
13154  return BuildInvalid();
13155  }
13156 
13157  UsingDecl *UD = BuildValid();
13158 
13159  // Some additional rules apply to inheriting constructors.
13160  if (UsingName.getName().getNameKind() ==
13162  // Suppress access diagnostics; the access check is instead performed at the
13163  // point of use for an inheriting constructor.
13164  R.suppressDiagnostics();
13166  return UD;
13167  }
13168 
13169  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
13170  UsingShadowDecl *PrevDecl = nullptr;
13171  if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
13172  BuildUsingShadowDecl(S, UD, *I, PrevDecl);
13173  }
13174 
13175  return UD;
13176 }
13177 
13179  SourceLocation UsingLoc,
13180  SourceLocation EnumLoc,
13181  SourceLocation NameLoc,
13183  EnumDecl *ED) {
13184  bool Invalid = false;
13185 
13186  if (CurContext->getRedeclContext()->isRecord()) {
13187  /// In class scope, check if this is a duplicate, for better a diagnostic.
13188  DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
13189  LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
13191 
13192  LookupName(Previous, S);
13193 
13194  for (NamedDecl *D : Previous)
13195  if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
13196  if (UED->getEnumDecl() == ED) {
13197  Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
13198  << SourceRange(EnumLoc, NameLoc);
13199  Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
13200  Invalid = true;
13201  break;
13202  }
13203  }
13204 
13205  if (RequireCompleteEnumDecl(ED, NameLoc))
13206  Invalid = true;
13207 
13209  EnumLoc, NameLoc, EnumType);
13210  UD->setAccess(AS);
13211  CurContext->addDecl(UD);
13212 
13213  if (Invalid) {
13214  UD->setInvalidDecl();
13215  return UD;
13216  }
13217 
13218  // Create the shadow decls for each enumerator
13219  for (EnumConstantDecl *EC : ED->enumerators()) {
13220  UsingShadowDecl *PrevDecl = nullptr;
13221  DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13224  LookupName(Previous, S);
13226 
13227  if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
13228  BuildUsingShadowDecl(S, UD, EC, PrevDecl);
13229  }
13230 
13231  return UD;
13232 }
13233 
13235  ArrayRef<NamedDecl *> Expansions) {
13236  assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13237  isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13238  isa<UsingPackDecl>(InstantiatedFrom));
13239 
13240  auto *UPD =
13241  UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
13242  UPD->setAccess(InstantiatedFrom->getAccess());
13243  CurContext->addDecl(UPD);
13244  return UPD;
13245 }
13246 
13247 /// Additional checks for a using declaration referring to a constructor name.
13249  assert(!UD->hasTypename() && "expecting a constructor name");
13250 
13251  const Type *SourceType = UD->getQualifier()->getAsType();
13252  assert(SourceType &&
13253  "Using decl naming constructor doesn't have type in scope spec.");
13254  CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
13255 
13256  // Check whether the named type is a direct base class.
13257  bool AnyDependentBases = false;
13258  auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
13259  AnyDependentBases);
13260  if (!Base && !AnyDependentBases) {
13261  Diag(UD->getUsingLoc(),
13262  diag::err_using_decl_constructor_not_in_direct_base)
13263  << UD->getNameInfo().getSourceRange()
13264  << QualType(SourceType, 0) << TargetClass;
13265  UD->setInvalidDecl();
13266  return true;
13267  }
13268 
13269  if (Base)
13270  Base->setInheritConstructors();
13271 
13272  return false;
13273 }
13274 
13275 /// Checks that the given using declaration is not an invalid
13276 /// redeclaration. Note that this is checking only for the using decl
13277 /// itself, not for any ill-formedness among the UsingShadowDecls.
13279  bool HasTypenameKeyword,
13280  const CXXScopeSpec &SS,
13281  SourceLocation NameLoc,
13282  const LookupResult &Prev) {
13283  NestedNameSpecifier *Qual = SS.getScopeRep();
13284 
13285  // C++03 [namespace.udecl]p8:
13286  // C++0x [namespace.udecl]p10:
13287  // A using-declaration is a declaration and can therefore be used
13288  // repeatedly where (and only where) multiple declarations are
13289  // allowed.
13290  //
13291  // That's in non-member contexts.
13292  if (!CurContext->getRedeclContext()->isRecord()) {
13293  // A dependent qualifier outside a class can only ever resolve to an
13294  // enumeration type. Therefore it conflicts with any other non-type
13295  // declaration in the same scope.
13296  // FIXME: How should we check for dependent type-type conflicts at block
13297  // scope?
13298  if (Qual->isDependent() && !HasTypenameKeyword) {
13299  for (auto *D : Prev) {
13300  if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
13301  bool OldCouldBeEnumerator =
13302  isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
13303  Diag(NameLoc,
13304  OldCouldBeEnumerator ? diag::err_redefinition
13305  : diag::err_redefinition_different_kind)
13306  << Prev.getLookupName();
13307  Diag(D->getLocation(), diag::note_previous_definition);
13308  return true;
13309  }
13310  }
13311  }
13312  return false;
13313  }
13314 
13315  const NestedNameSpecifier *CNNS =
13317  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
13318  NamedDecl *D = *I;
13319 
13320  bool DTypename;
13321  NestedNameSpecifier *DQual;
13322  if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
13323  DTypename = UD->hasTypename();
13324  DQual = UD->getQualifier();
13325  } else if (UnresolvedUsingValueDecl *UD
13326  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
13327  DTypename = false;
13328  DQual = UD->getQualifier();
13329  } else if (UnresolvedUsingTypenameDecl *UD
13330  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
13331  DTypename = true;
13332  DQual = UD->getQualifier();
13333  } else continue;
13334 
13335  // using decls differ if one says 'typename' and the other doesn't.
13336  // FIXME: non-dependent using decls?
13337  if (HasTypenameKeyword != DTypename) continue;
13338 
13339  // using decls differ if they name different scopes (but note that
13340  // template instantiation can cause this check to trigger when it
13341  // didn't before instantiation).
13342  if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
13343  continue;
13344 
13345  Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
13346  Diag(D->getLocation(), diag::note_using_decl) << 1;
13347  return true;
13348  }
13349 
13350  return false;
13351 }
13352 
13353 /// Checks that the given nested-name qualifier used in a using decl
13354 /// in the current context is appropriately related to the current
13355 /// scope. If an error is found, diagnoses it and returns true.
13356 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the
13357 /// result of that lookup. UD is likewise nullptr, except when we have an
13358 /// already-populated UsingDecl whose shadow decls contain the same information
13359 /// (i.e. we're instantiating a UsingDecl with non-dependent scope).
13360 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13361  const CXXScopeSpec &SS,
13362  const DeclarationNameInfo &NameInfo,
13363  SourceLocation NameLoc,
13364  const LookupResult *R, const UsingDecl *UD) {
13365  DeclContext *NamedContext = computeDeclContext(SS);
13366  assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13367  "resolvable context must have exactly one set of decls");
13368 
13369  // C++ 20 permits using an enumerator that does not have a class-hierarchy
13370  // relationship.
13371  bool Cxx20Enumerator = false;
13372  if (NamedContext) {
13373  EnumConstantDecl *EC = nullptr;
13374  if (R)
13375  EC = R->getAsSingle<EnumConstantDecl>();
13376  else if (UD && UD->shadow_size() == 1)
13377  EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
13378  if (EC)
13379  Cxx20Enumerator = getLangOpts().CPlusPlus20;
13380 
13381  if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
13382  // C++14 [namespace.udecl]p7:
13383  // A using-declaration shall not name a scoped enumerator.
13384  // C++20 p1099 permits enumerators.
13385  if (EC && R && ED->isScoped())
13386  Diag(SS.getBeginLoc(),
13388  ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13389  : diag::ext_using_decl_scoped_enumerator)
13390  << SS.getRange();
13391 
13392  // We want to consider the scope of the enumerator
13393  NamedContext = ED->getDeclContext();
13394  }
13395  }
13396 
13397  if (!CurContext->isRecord()) {
13398  // C++03 [namespace.udecl]p3:
13399  // C++0x [namespace.udecl]p8:
13400  // A using-declaration for a class member shall be a member-declaration.
13401  // C++20 [namespace.udecl]p7
13402  // ... other than an enumerator ...
13403 
13404  // If we weren't able to compute a valid scope, it might validly be a
13405  // dependent class or enumeration scope. If we have a 'typename' keyword,
13406  // the scope must resolve to a class type.
13407  if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13408  : !HasTypename)
13409  return false; // OK
13410 
13411  Diag(NameLoc,
13412  Cxx20Enumerator
13413  ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13414  : diag::err_using_decl_can_not_refer_to_class_member)
13415  << SS.getRange();
13416 
13417  if (Cxx20Enumerator)
13418  return false; // OK
13419 
13420  auto *RD = NamedContext
13421  ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
13422  : nullptr;
13423  if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
13424  // See if there's a helpful fixit
13425 
13426  if (!R) {
13427  // We will have already diagnosed the problem on the template
13428  // definition, Maybe we should do so again?
13429  } else if (R->getAsSingle<TypeDecl>()) {
13430  if (getLangOpts().CPlusPlus11) {
13431  // Convert 'using X::Y;' to 'using Y = X::Y;'.
13432  Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
13433  << 0 // alias declaration
13435  NameInfo.getName().getAsString() +
13436  " = ");
13437  } else {
13438  // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13439  SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
13440  Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
13441  << 1 // typedef declaration
13442  << FixItHint::CreateReplacement(UsingLoc, "typedef")
13444  InsertLoc, " " + NameInfo.getName().getAsString());
13445  }
13446  } else if (R->getAsSingle<VarDecl>()) {
13447  // Don't provide a fixit outside C++11 mode; we don't want to suggest
13448  // repeating the type of the static data member here.
13449  FixItHint FixIt;
13450  if (getLangOpts().CPlusPlus11) {
13451  // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13453  UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
13454  }
13455 
13456  Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13457  << 2 // reference declaration
13458  << FixIt;
13459  } else if (R->getAsSingle<EnumConstantDecl>()) {
13460  // Don't provide a fixit outside C++11 mode; we don't want to suggest
13461  // repeating the type of the enumeration here, and we can't do so if
13462  // the type is anonymous.
13463  FixItHint FixIt;
13464  if (getLangOpts().CPlusPlus11) {
13465  // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13467  UsingLoc,
13468  "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13469  }
13470 
13471  Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13472  << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
13473  << FixIt;
13474  }
13475  }
13476 
13477  return true; // Fail
13478  }
13479 
13480  // If the named context is dependent, we can't decide much.
13481  if (!NamedContext) {
13482  // FIXME: in C++0x, we can diagnose if we can prove that the
13483  // nested-name-specifier does not refer to a base class, which is
13484  // still possible in some cases.
13485 
13486  // Otherwise we have to conservatively report that things might be
13487  // okay.
13488  return false;
13489  }
13490 
13491  // The current scope is a record.
13492  if (!NamedContext->isRecord()) {
13493  // Ideally this would point at the last name in the specifier,
13494  // but we don't have that level of source info.
13495  Diag(SS.getBeginLoc(),
13496  Cxx20Enumerator
13497  ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13498  : diag::err_using_decl_nested_name_specifier_is_not_class)
13499  << SS.getScopeRep() << SS.getRange();
13500 
13501  if (Cxx20Enumerator)
13502  return false; // OK
13503 
13504  return true;
13505  }
13506 
13507  if (!NamedContext->isDependentContext() &&
13508  RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
13509  return true;
13510 
13511  if (getLangOpts().CPlusPlus11) {
13512  // C++11 [namespace.udecl]p3:
13513  // In a using-declaration used as a member-declaration, the
13514  // nested-name-specifier shall name a base class of the class
13515  // being defined.
13516 
13517  if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
13518  cast<CXXRecordDecl>(NamedContext))) {
13519 
13520  if (Cxx20Enumerator) {
13521  Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13522  << SS.getRange();
13523  return false;
13524  }
13525 
13526  if (CurContext == NamedContext) {
13527  Diag(SS.getBeginLoc(),
13528  diag::err_using_decl_nested_name_specifier_is_current_class)
13529  << SS.getRange();
13530  return !getLangOpts().CPlusPlus20;
13531  }
13532 
13533  if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
13534  Diag(SS.getBeginLoc(),
13535  diag::err_using_decl_nested_name_specifier_is_not_base_class)
13536  << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
13537  << SS.getRange();
13538  }
13539  return true;
13540  }
13541 
13542  return false;
13543  }
13544 
13545  // C++03 [namespace.udecl]p4:
13546  // A using-declaration used as a member-declaration shall refer
13547  // to a member of a base class of the class being defined [etc.].
13548 
13549  // Salient point: SS doesn't have to name a base class as long as
13550  // lookup only finds members from base classes. Therefore we can
13551  // diagnose here only if we can prove that can't happen,
13552  // i.e. if the class hierarchies provably don't intersect.
13553 
13554  // TODO: it would be nice if "definitely valid" results were cached
13555  // in the UsingDecl and UsingShadowDecl so that these checks didn't
13556  // need to be repeated.
13557 
13559  auto Collect = [&Bases](const CXXRecordDecl *Base) {
13560  Bases.insert(Base);
13561  return true;
13562  };
13563 
13564  // Collect all bases. Return false if we find a dependent base.
13565  if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
13566  return false;
13567 
13568  // Returns true if the base is dependent or is one of the accumulated base
13569  // classes.
13570  auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
13571  return !Bases.count(Base);
13572  };
13573 
13574  // Return false if the class has a dependent base or if it or one
13575  // of its bases is present in the base set of the current context.
13576  if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
13577  !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
13578  return false;
13579 
13580  Diag(SS.getRange().getBegin(),
13581  diag::err_using_decl_nested_name_specifier_is_not_base_class)
13582  << SS.getScopeRep()
13583  << cast<CXXRecordDecl>(CurContext)
13584  << SS.getRange();
13585 
13586  return true;
13587 }
13588 
13590  MultiTemplateParamsArg TemplateParamLists,
13591  SourceLocation UsingLoc, UnqualifiedId &Name,
13592  const ParsedAttributesView &AttrList,
13593  TypeResult Type, Decl *DeclFromDeclSpec) {
13594  // Get the innermost enclosing declaration scope.
13595  S = S->getDeclParent();
13596 
13597  if (Type.isInvalid())
13598  return nullptr;
13599 
13600  bool Invalid = false;
13602  TypeSourceInfo *TInfo = nullptr;
13603  GetTypeFromParser(Type.get(), &TInfo);
13604 
13605  if (DiagnoseClassNameShadow(CurContext, NameInfo))
13606  return nullptr;
13607 
13608  if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
13610  Invalid = true;
13612  TInfo->getTypeLoc().getBeginLoc());
13613  }
13614 
13615  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13616  TemplateParamLists.size()
13619  LookupName(Previous, S);
13620 
13621  // Warn about shadowing the name of a template parameter.
13622  if (Previous.isSingleResult() &&
13623  Previous.getFoundDecl()->isTemplateParameter()) {
13624  DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
13625  Previous.clear();
13626  }
13627 
13628  assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13629  "name in alias declaration must be an identifier");
13631  Name.StartLocation,
13632  Name.Identifier, TInfo);
13633 
13634  NewTD->setAccess(AS);
13635 
13636  if (Invalid)
13637  NewTD->setInvalidDecl();
13638 
13639  ProcessDeclAttributeList(S, NewTD, AttrList);
13640  AddPragmaAttributes(S, NewTD);
13641  ProcessAPINotes(NewTD);
13642 
13644  Invalid |= NewTD->isInvalidDecl();
13645 
13646  bool Redeclaration = false;
13647 
13648  NamedDecl *NewND;
13649  if (TemplateParamLists.size()) {
13650  TypeAliasTemplateDecl *OldDecl = nullptr;
13651  TemplateParameterList *OldTemplateParams = nullptr;
13652 
13653  if (TemplateParamLists.size() != 1) {
13654  Diag(UsingLoc, diag::err_alias_template_extra_headers)
13655  << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13656  TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13657  Invalid = true;
13658  }
13659  TemplateParameterList *TemplateParams = TemplateParamLists[0];
13660 
13661  // Check that we can declare a template here.
13662  if (CheckTemplateDeclScope(S, TemplateParams))
13663  return nullptr;
13664 
13665  // Only consider previous declarations in the same scope.
13666  FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13667  /*ExplicitInstantiationOrSpecialization*/false);
13668  if (!Previous.empty()) {
13669  Redeclaration = true;
13670 
13671  OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13672  if (!OldDecl && !Invalid) {
13673  Diag(UsingLoc, diag::err_redefinition_different_kind)
13674  << Name.Identifier;
13675 
13676  NamedDecl *OldD = Previous.getRepresentativeDecl();
13677  if (OldD->getLocation().isValid())
13678  Diag(OldD->getLocation(), diag::note_previous_definition);
13679 
13680  Invalid = true;
13681  }
13682 
13683  if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13684  if (TemplateParameterListsAreEqual(TemplateParams,
13685  OldDecl->getTemplateParameters(),
13686  /*Complain=*/true,
13688  OldTemplateParams =
13690  else
13691  Invalid = true;
13692 
13693  TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13694  if (!Invalid &&
13696  NewTD->getUnderlyingType())) {
13697  // FIXME: The C++0x standard does not clearly say this is ill-formed,
13698  // but we can't reasonably accept it.
13699  Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13700  << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13701  if (OldTD->getLocation().isValid())
13702  Diag(OldTD->getLocation(), diag::note_previous_definition);
13703  Invalid = true;
13704  }
13705  }
13706  }
13707 
13708  // Merge any previous default template arguments into our parameters,
13709  // and check the parameter list.
13710  if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13712  return nullptr;
13713 
13714  TypeAliasTemplateDecl *NewDecl =
13716  Name.Identifier, TemplateParams,
13717  NewTD);
13718  NewTD->setDescribedAliasTemplate(NewDecl);
13719 
13720  NewDecl->setAccess(AS);
13721 
13722  if (Invalid)
13723  NewDecl->setInvalidDecl();
13724  else if (OldDecl) {
13725  NewDecl->setPreviousDecl(OldDecl);
13726  CheckRedeclarationInModule(NewDecl, OldDecl);
13727  }
13728 
13729  NewND = NewDecl;
13730  } else {
13731  if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13732  setTagNameForLinkagePurposes(TD, NewTD);
13733  handleTagNumbering(TD, S);
13734  }
13735  ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13736  NewND = NewTD;
13737  }
13738 
13739  PushOnScopeChains(NewND, S);
13740  ActOnDocumentableDecl(NewND);
13741  return NewND;
13742 }
13743 
13745  SourceLocation AliasLoc,
13746  IdentifierInfo *Alias, CXXScopeSpec &SS,
13747  SourceLocation IdentLoc,
13748  IdentifierInfo *Ident) {
13749 
13750  // Lookup the namespace name.
13751  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13752  LookupParsedName(R, S, &SS);
13753 
13754  if (R.isAmbiguous())
13755  return nullptr;
13756 
13757  if (R.empty()) {
13758  if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13759  Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13760  return nullptr;
13761  }
13762  }
13763  assert(!R.isAmbiguous() && !R.empty());
13764  NamedDecl *ND = R.getRepresentativeDecl();
13765 
13766  // Check if we have a previous declaration with the same name.
13767  LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13769  LookupName(PrevR, S);
13770 
13771  // Check we're not shadowing a template parameter.
13772  if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13773  DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
13774  PrevR.clear();
13775  }
13776 
13777  // Filter out any other lookup result from an enclosing scope.
13778  FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13779  /*AllowInlineNamespace*/false);
13780 
13781  // Find the previous declaration and check that we can redeclare it.
13782  NamespaceAliasDecl *Prev = nullptr;
13783  if (PrevR.isSingleResult()) {
13784  NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13785  if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13786  // We already have an alias with the same name that points to the same
13787  // namespace; check that it matches.
13788  if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13789  Prev = AD;
13790  } else if (isVisible(PrevDecl)) {
13791  Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13792  << Alias;
13793  Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13794  << AD->getNamespace();
13795  return nullptr;
13796  }
13797  } else if (isVisible(PrevDecl)) {
13798  unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13799  ? diag::err_redefinition
13800  : diag::err_redefinition_different_kind;
13801  Diag(AliasLoc, DiagID) << Alias;
13802  Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13803  return nullptr;
13804  }
13805  }
13806 
13807  // The use of a nested name specifier may trigger deprecation warnings.
13808  DiagnoseUseOfDecl(ND, IdentLoc);
13809 
13811  NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13812  Alias, SS.getWithLocInContext(Context),
13813  IdentLoc, ND);
13814  if (Prev)
13815  AliasDecl->setPreviousDecl(Prev);
13816 
13818  return AliasDecl;
13819 }
13820 
13821 namespace {
13822 struct SpecialMemberExceptionSpecInfo
13823  : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13824  SourceLocation Loc;
13826 
13827  SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13830  SourceLocation Loc)
13831  : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13832 
13833  bool visitBase(CXXBaseSpecifier *Base);
13834  bool visitField(FieldDecl *FD);
13835 
13836  void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13837  unsigned Quals);
13838 
13839  void visitSubobjectCall(Subobject Subobj,
13841 };
13842 }
13843 
13844 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13845  auto *RT = Base->getType()->getAs<RecordType>();
13846  if (!RT)
13847  return false;
13848 
13849  auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13850  Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13851  if (auto *BaseCtor = SMOR.getMethod()) {
13852  visitSubobjectCall(Base, BaseCtor);
13853  return false;
13854  }
13855 
13856  visitClassSubobject(BaseClass, Base, 0);
13857  return false;
13858 }
13859 
13860 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13862  FD->hasInClassInitializer()) {
13863  Expr *E = FD->getInClassInitializer();
13864  if (!E)
13865  // FIXME: It's a little wasteful to build and throw away a
13866  // CXXDefaultInitExpr here.
13867  // FIXME: We should have a single context note pointing at Loc, and
13868  // this location should be MD->getLocation() instead, since that's
13869  // the location where we actually use the default init expression.
13870  E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13871  if (E)
13872  ExceptSpec.CalledExpr(E);
13873  } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13874  ->getAs<RecordType>()) {
13875  visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13876  FD->getType().getCVRQualifiers());
13877  }
13878  return false;
13879 }
13880 
13881 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13882  Subobject Subobj,
13883  unsigned Quals) {
13884  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13885  bool IsMutable = Field && Field->isMutable();
13886  visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13887 }
13888 
13889 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13890  Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13891  // Note, if lookup fails, it doesn't matter what exception specification we
13892  // choose because the special member will be deleted.
13893  if (CXXMethodDecl *MD = SMOR.getMethod())
13894  ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13895 }
13896 
13898  llvm::APSInt Result;
13900  ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13901  ExplicitSpec.setExpr(Converted.get());
13902  if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13903  ExplicitSpec.setKind(Result.getBoolValue()
13906  return true;
13907  }
13908  ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
13909  return false;
13910 }
13911 
13914  if (!ExplicitExpr->isTypeDependent())
13916  return ES;
13917 }
13918 
13923  ComputingExceptionSpec CES(S, MD, Loc);
13924 
13925  CXXRecordDecl *ClassDecl = MD->getParent();
13926 
13927  // C++ [except.spec]p14:
13928  // An implicitly declared special member function (Clause 12) shall have an
13929  // exception-specification. [...]
13930  SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13931  if (ClassDecl->isInvalidDecl())
13932  return Info.ExceptSpec;
13933 
13934  // FIXME: If this diagnostic fires, we're probably missing a check for
13935  // attempting to resolve an exception specification before it's known
13936  // at a higher level.
13937  if (S.RequireCompleteType(MD->getLocation(),
13938  S.Context.getRecordType(ClassDecl),
13939  diag::err_exception_spec_incomplete_type))
13940  return Info.ExceptSpec;
13941 
13942  // C++1z [except.spec]p7:
13943  // [Look for exceptions thrown by] a constructor selected [...] to
13944  // initialize a potentially constructed subobject,
13945  // C++1z [except.spec]p8:
13946  // The exception specification for an implicitly-declared destructor, or a
13947  // destructor without a noexcept-specifier, is potentially-throwing if and
13948  // only if any of the destructors for any of its potentially constructed
13949  // subojects is potentially throwing.
13950  // FIXME: We respect the first rule but ignore the "potentially constructed"
13951  // in the second rule to resolve a core issue (no number yet) that would have
13952  // us reject:
13953  // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13954  // struct B : A {};
13955  // struct C : B { void f(); };
13956  // ... due to giving B::~B() a non-throwing exception specification.
13957  Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13958  : Info.VisitAllBases);
13959 
13960  return Info.ExceptSpec;
13961 }
13962 
13963 namespace {
13964 /// RAII object to register a special member as being currently declared.
13965 struct DeclaringSpecialMember {
13966  Sema &S;
13968  Sema::ContextRAII SavedContext;
13969  bool WasAlreadyBeingDeclared;
13970 
13971  DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
13972  : S(S), D(RD, CSM), SavedContext(S, RD) {
13973  WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
13974  if (WasAlreadyBeingDeclared)
13975  // This almost never happens, but if it does, ensure that our cache
13976  // doesn't contain a stale result.
13977  S.SpecialMemberCache.clear();
13978  else {
13979  // Register a note to be produced if we encounter an error while
13980  // declaring the special member.
13983  // FIXME: We don't have a location to use here. Using the class's
13984  // location maintains the fiction that we declare all special members
13985  // with the class, but (1) it's not clear that lying about that helps our
13986  // users understand what's going on, and (2) there may be outer contexts
13987  // on the stack (some of which are relevant) and printing them exposes
13988  // our lies.
13989  Ctx.PointOfInstantiation = RD->getLocation();
13990  Ctx.Entity = RD;
13991  Ctx.SpecialMember = CSM;
13992  S.pushCodeSynthesisContext(Ctx);
13993  }
13994  }
13995  ~DeclaringSpecialMember() {
13996  if (!WasAlreadyBeingDeclared) {
13997  S.SpecialMembersBeingDeclared.erase(D);
13999  }
14000  }
14001 
14002  /// Are we already trying to declare this special member?
14003  bool isAlreadyBeingDeclared() const {
14004  return WasAlreadyBeingDeclared;
14005  }
14006 };
14007 }
14008 
14010  // Look up any existing declarations, but don't trigger declaration of all
14011  // implicit special members with this name.
14012  DeclarationName Name = FD->getDeclName();
14015  for (auto *D : FD->getParent()->lookup(Name))
14016  if (auto *Acceptable = R.getAcceptableDecl(D))
14017  R.addDecl(Acceptable);
14018  R.resolveKind();
14019  R.suppressDiagnostics();
14020 
14021  CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
14023 }
14024 
14025 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
14026  QualType ResultTy,
14027  ArrayRef<QualType> Args) {
14028  // Build an exception specification pointing back at this constructor.
14029  FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
14030 
14032  if (AS != LangAS::Default) {
14033  EPI.TypeQuals.addAddressSpace(AS);
14034  }
14035 
14036  auto QT = Context.getFunctionType(ResultTy, Args, EPI);
14037  SpecialMem->setType(QT);
14038 
14039  // During template instantiation of implicit special member functions we need
14040  // a reliable TypeSourceInfo for the function prototype in order to allow
14041  // functions to be substituted.
14042  if (inTemplateInstantiation() &&
14043  cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
14044  TypeSourceInfo *TSI =
14045  Context.getTrivialTypeSourceInfo(SpecialMem->getType());
14046  SpecialMem->setTypeSourceInfo(TSI);
14047  }
14048 }
14049 
14051  CXXRecordDecl *ClassDecl) {
14052  // C++ [class.ctor]p5:
14053  // A default constructor for a class X is a constructor of class X
14054  // that can be called without an argument. If there is no
14055  // user-declared constructor for class X, a default constructor is
14056  // implicitly declared. An implicitly-declared default constructor
14057  // is an inline public member of its class.
14058  assert(ClassDecl->needsImplicitDefaultConstructor() &&
14059  "Should not build implicit default constructor!");
14060 
14061  DeclaringSpecialMember DSM(*this, ClassDecl,
14063  if (DSM.isAlreadyBeingDeclared())
14064  return nullptr;
14065 
14067  *this, ClassDecl, CXXSpecialMemberKind::DefaultConstructor, false);
14068 
14069  // Create the actual constructor declaration.
14070  CanQualType ClassType
14072  SourceLocation ClassLoc = ClassDecl->getLocation();
14073  DeclarationName Name
14075  DeclarationNameInfo NameInfo(Name, ClassLoc);
14077  Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
14078  /*TInfo=*/nullptr, ExplicitSpecifier(),
14079  getCurFPFeatures().isFPConstrained(),
14080  /*isInline=*/true, /*isImplicitlyDeclared=*/true,
14083  DefaultCon->setAccess(AS_public);
14084  DefaultCon->setDefaulted();
14085 
14086  setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, std::nullopt);
14087 
14088  if (getLangOpts().CUDA)
14090  ClassDecl, CXXSpecialMemberKind::DefaultConstructor, DefaultCon,
14091  /* ConstRHS */ false,
14092  /* Diagnose */ false);
14093 
14094  // We don't need to use SpecialMemberIsTrivial here; triviality for default
14095  // constructors is easy to compute.
14096  DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
14097 
14098  // Note that we have declared this constructor.
14100 
14101  Scope *S = getScopeForContext(ClassDecl);
14103 
14104  if (ShouldDeleteSpecialMember(DefaultCon,
14106  SetDeclDeleted(DefaultCon, ClassLoc);
14107 
14108  if (S)
14109  PushOnScopeChains(DefaultCon, S, false);
14110  ClassDecl->addDecl(DefaultCon);
14111 
14112  return DefaultCon;
14113 }
14114 
14116  CXXConstructorDecl *Constructor) {
14117  assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
14118  !Constructor->doesThisDeclarationHaveABody() &&
14119  !Constructor->isDeleted()) &&
14120  "DefineImplicitDefaultConstructor - call it for implicit default ctor");
14121  if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14122  return;
14123 
14124  CXXRecordDecl *ClassDecl = Constructor->getParent();
14125  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
14126  if (ClassDecl->isInvalidDecl()) {
14127  return;
14128  }
14129 
14130  SynthesizedFunctionScope Scope(*this, Constructor);
14131 
14132  // The exception specification is needed because we are defining the
14133  // function.
14134  ResolveExceptionSpec(CurrentLocation,
14135  Constructor->getType()->castAs<FunctionProtoType>());
14136  MarkVTableUsed(CurrentLocation, ClassDecl);
14137 
14138  // Add a context note for diagnostics produced after this point.
14139  Scope.addContextNote(CurrentLocation);
14140 
14141  if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
14142  Constructor->setInvalidDecl();
14143  return;
14144  }
14145 
14146  SourceLocation Loc = Constructor->getEndLoc().isValid()
14147  ? Constructor->getEndLoc()
14148  : Constructor->getLocation();
14149  Constructor->setBody(new (Context) CompoundStmt(Loc));
14150  Constructor->markUsed(Context);
14151 
14153  L->CompletedImplicitDefinition(Constructor);
14154  }
14155 
14156  DiagnoseUninitializedFields(*this, Constructor);
14157 }
14158 
14160  // Perform any delayed checks on exception specifications.
14162 }
14163 
14164 /// Find or create the fake constructor we synthesize to model constructing an
14165 /// object of a derived class via a constructor of a base class.
14168  CXXConstructorDecl *BaseCtor,
14169  ConstructorUsingShadowDecl *Shadow) {
14170  CXXRecordDecl *Derived = Shadow->getParent();
14171  SourceLocation UsingLoc = Shadow->getLocation();
14172 
14173  // FIXME: Add a new kind of DeclarationName for an inherited constructor.
14174  // For now we use the name of the base class constructor as a member of the
14175  // derived class to indicate a (fake) inherited constructor name.
14176  DeclarationName Name = BaseCtor->getDeclName();
14177 
14178  // Check to see if we already have a fake constructor for this inherited
14179  // constructor call.
14180  for (NamedDecl *Ctor : Derived->lookup(Name))
14181  if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
14182  ->getInheritedConstructor()
14183  .getConstructor(),
14184  BaseCtor))
14185  return cast<CXXConstructorDecl>(Ctor);
14186 
14187  DeclarationNameInfo NameInfo(Name, UsingLoc);
14188  TypeSourceInfo *TInfo =
14189  Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
14190  FunctionProtoTypeLoc ProtoLoc =
14192 
14193  // Check the inherited constructor is valid and find the list of base classes
14194  // from which it was inherited.
14195  InheritedConstructorInfo ICI(*this, Loc, Shadow);
14196 
14197  bool Constexpr = BaseCtor->isConstexpr() &&
14200  false, BaseCtor, &ICI);
14201 
14203  Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
14204  BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
14205  /*isInline=*/true,
14206  /*isImplicitlyDeclared=*/true,
14208  InheritedConstructor(Shadow, BaseCtor),
14209  BaseCtor->getTrailingRequiresClause());
14210  if (Shadow->isInvalidDecl())
14211  DerivedCtor->setInvalidDecl();
14212 
14213  // Build an unevaluated exception specification for this fake constructor.
14214  const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
14217  EPI.ExceptionSpec.SourceDecl = DerivedCtor;
14218  DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
14219  FPT->getParamTypes(), EPI));
14220 
14221  // Build the parameter declarations.
14222  SmallVector<ParmVarDecl *, 16> ParamDecls;
14223  for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14224  TypeSourceInfo *TInfo =
14225  Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
14227  Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
14228  FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
14229  PD->setScopeInfo(0, I);
14230  PD->setImplicit();
14231  // Ensure attributes are propagated onto parameters (this matters for
14232  // format, pass_object_size, ...).
14233  mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
14234  ParamDecls.push_back(PD);
14235  ProtoLoc.setParam(I, PD);
14236  }
14237 
14238  // Set up the new constructor.
14239  assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14240  DerivedCtor->setAccess(BaseCtor->getAccess());
14241  DerivedCtor->setParams(ParamDecls);
14242  Derived->addDecl(DerivedCtor);
14243 
14244  if (ShouldDeleteSpecialMember(DerivedCtor,
14246  SetDeclDeleted(DerivedCtor, UsingLoc);
14247 
14248  return DerivedCtor;
14249 }
14250 
14252  InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
14255  &ICI,
14256  /*Diagnose*/ true);
14257 }
14258 
14260  CXXConstructorDecl *Constructor) {
14261  CXXRecordDecl *ClassDecl = Constructor->getParent();
14262  assert(Constructor->getInheritedConstructor() &&
14263  !Constructor->doesThisDeclarationHaveABody() &&
14264  !Constructor->isDeleted());
14265  if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14266  return;
14267 
14268  // Initializations are performed "as if by a defaulted default constructor",
14269  // so enter the appropriate scope.
14270  SynthesizedFunctionScope Scope(*this, Constructor);
14271 
14272  // The exception specification is needed because we are defining the
14273  // function.
14274  ResolveExceptionSpec(CurrentLocation,
14275  Constructor->getType()->castAs<FunctionProtoType>());
14276  MarkVTableUsed(CurrentLocation, ClassDecl);
14277 
14278  // Add a context note for diagnostics produced after this point.
14279  Scope.addContextNote(CurrentLocation);
14280 
14281  ConstructorUsingShadowDecl *Shadow =
14282  Constructor->getInheritedConstructor().getShadowDecl();
14283  CXXConstructorDecl *InheritedCtor =
14284  Constructor->getInheritedConstructor().getConstructor();
14285 
14286  // [class.inhctor.init]p1:
14287  // initialization proceeds as if a defaulted default constructor is used to
14288  // initialize the D object and each base class subobject from which the
14289  // constructor was inherited
14290 
14291  InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14292  CXXRecordDecl *RD = Shadow->getParent();
14293  SourceLocation InitLoc = Shadow->getLocation();
14294 
14295  // Build explicit initializers for all base classes from which the
14296  // constructor was inherited.
14298  for (bool VBase : {false, true}) {
14299  for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14300  if (B.isVirtual() != VBase)
14301  continue;
14302 
14303  auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14304  if (!BaseRD)
14305  continue;
14306 
14307  auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
14308  if (!BaseCtor.first)
14309  continue;
14310 
14311  MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
14313  InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14314 
14315  auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
14316  Inits.push_back(new (Context) CXXCtorInitializer(
14317  Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14318  SourceLocation()));
14319  }
14320  }
14321 
14322  // We now proceed as if for a defaulted default constructor, with the relevant
14323  // initializers replaced.
14324 
14325  if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
14326  Constructor->setInvalidDecl();
14327  return;
14328  }
14329 
14330  Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14331  Constructor->markUsed(Context);
14332 
14334  L->CompletedImplicitDefinition(Constructor);
14335  }
14336 
14337  DiagnoseUninitializedFields(*this, Constructor);
14338 }
14339 
14341  // C++ [class.dtor]p2:
14342  // If a class has no user-declared destructor, a destructor is
14343  // declared implicitly. An implicitly-declared destructor is an
14344  // inline public member of its class.
14345  assert(ClassDecl->needsImplicitDestructor());
14346 
14347  DeclaringSpecialMember DSM(*this, ClassDecl,
14349  if (DSM.isAlreadyBeingDeclared())
14350  return nullptr;
14351 
14353  *this, ClassDecl, CXXSpecialMemberKind::Destructor, false);
14354 
14355  // Create the actual destructor declaration.
14356  CanQualType ClassType
14358  SourceLocation ClassLoc = ClassDecl->getLocation();
14359  DeclarationName Name
14361  DeclarationNameInfo NameInfo(Name, ClassLoc);
14363  Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
14364  getCurFPFeatures().isFPConstrained(),
14365  /*isInline=*/true,
14366  /*isImplicitlyDeclared=*/true,
14369  Destructor->setAccess(AS_public);
14370  Destructor->setDefaulted();
14371 
14372  setupImplicitSpecialMemberType(Destructor, Context.VoidTy, std::nullopt);
14373 
14374  if (getLangOpts().CUDA)
14376  ClassDecl, CXXSpecialMemberKind::Destructor, Destructor,
14377  /* ConstRHS */ false,
14378  /* Diagnose */ false);
14379 
14380  // We don't need to use SpecialMemberIsTrivial here; triviality for
14381  // destructors is easy to compute.
14382  Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14383  Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14384  ClassDecl->hasTrivialDestructorForCall());
14385 
14386  // Note that we have declared this destructor.
14388 
14389  Scope *S = getScopeForContext(ClassDecl);
14391 
14392  // We can't check whether an implicit destructor is deleted before we complete
14393  // the definition of the class, because its validity depends on the alignment
14394  // of the class. We'll check this from ActOnFields once the class is complete.
14395  if (ClassDecl->isCompleteDefinition() &&
14397  SetDeclDeleted(Destructor, ClassLoc);
14398 
14399  // Introduce this destructor into its scope.
14400  if (S)
14401  PushOnScopeChains(Destructor, S, false);
14402  ClassDecl->addDecl(Destructor);
14403 
14404  return Destructor;
14405 }
14406 
14408  CXXDestructorDecl *Destructor) {
14409  assert((Destructor->isDefaulted() &&
14410  !Destructor->doesThisDeclarationHaveABody() &&
14411  !Destructor->isDeleted()) &&
14412  "DefineImplicitDestructor - call it for implicit default dtor");
14413  if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14414  return;
14415 
14416  CXXRecordDecl *ClassDecl = Destructor->getParent();
14417  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14418 
14419  SynthesizedFunctionScope Scope(*this, Destructor);
14420 
14421  // The exception specification is needed because we are defining the
14422  // function.
14423  ResolveExceptionSpec(CurrentLocation,
14424  Destructor->getType()->castAs<FunctionProtoType>());
14425  MarkVTableUsed(CurrentLocation, ClassDecl);
14426 
14427  // Add a context note for diagnostics produced after this point.
14428  Scope.addContextNote(CurrentLocation);
14429 
14430  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14431  Destructor->getParent());
14432 
14433  if (CheckDestructor(Destructor)) {
14434  Destructor->setInvalidDecl();
14435  return;
14436  }
14437 
14438  SourceLocation Loc = Destructor->getEndLoc().isValid()
14439  ? Destructor->getEndLoc()
14440  : Destructor->getLocation();
14441  Destructor->setBody(new (Context) CompoundStmt(Loc));
14442  Destructor->markUsed(Context);
14443 
14445  L->CompletedImplicitDefinition(Destructor);
14446  }
14447 }
14448 
14450  CXXDestructorDecl *Destructor) {
14451  if (Destructor->isInvalidDecl())
14452  return;
14453 
14454  CXXRecordDecl *ClassDecl = Destructor->getParent();
14455  assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14456  "implicit complete dtors unneeded outside MS ABI");
14457  assert(ClassDecl->getNumVBases() > 0 &&
14458  "complete dtor only exists for classes with vbases");
14459 
14460  SynthesizedFunctionScope Scope(*this, Destructor);
14461 
14462  // Add a context note for diagnostics produced after this point.
14463  Scope.addContextNote(CurrentLocation);
14464 
14465  MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
14466 }
14467 
14468 /// Perform any semantic analysis which needs to be delayed until all
14469 /// pending class member declarations have been parsed.
14471  // If the context is an invalid C++ class, just suppress these checks.
14472  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
14473  if (Record->isInvalidDecl()) {
14476  return;
14477  }
14479  }
14480 }
14481 
14484 
14485  if (!DelayedDllExportMemberFunctions.empty()) {
14487  std::swap(DelayedDllExportMemberFunctions, WorkList);
14488  for (CXXMethodDecl *M : WorkList) {
14489  DefineDefaultedFunction(*this, M, M->getLocation());
14490 
14491  // Pass the method to the consumer to get emitted. This is not necessary
14492  // for explicit instantiation definitions, as they will get emitted
14493  // anyway.
14494  if (M->getParent()->getTemplateSpecializationKind() !=
14497  }
14498  }
14499 }
14500 
14502  if (!DelayedDllExportClasses.empty()) {
14503  // Calling ReferenceDllExportedMembers might cause the current function to
14504  // be called again, so use a local copy of DelayedDllExportClasses.
14506  std::swap(DelayedDllExportClasses, WorkList);
14507  for (CXXRecordDecl *Class : WorkList)
14509  }
14510 }
14511 
14513  assert(getLangOpts().CPlusPlus11 &&
14514  "adjusting dtor exception specs was introduced in c++11");
14515 
14516  if (Destructor->isDependentContext())
14517  return;
14518 
14519  // C++11 [class.dtor]p3:
14520  // A declaration of a destructor that does not have an exception-
14521  // specification is implicitly considered to have the same exception-
14522  // specification as an implicit declaration.
14523  const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14524  if (DtorType->hasExceptionSpec())
14525  return;
14526 
14527  // Replace the destructor's type, building off the existing one. Fortunately,
14528  // the only thing of interest in the destructor type is its extended info.
14529  // The return and arguments are fixed.
14530  FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14532  EPI.ExceptionSpec.SourceDecl = Destructor;
14533  Destructor->setType(
14534  Context.getFunctionType(Context.VoidTy, std::nullopt, EPI));
14535 
14536  // FIXME: If the destructor has a body that could throw, and the newly created
14537  // spec doesn't allow exceptions, we should emit a warning, because this
14538  // change in behavior can break conforming C++03 programs at runtime.
14539  // However, we don't have a body or an exception specification yet, so it
14540  // needs to be done somewhere else.
14541 }
14542 
14543 namespace {
14544 /// An abstract base class for all helper classes used in building the
14545 // copy/move operators. These classes serve as factory functions and help us
14546 // avoid using the same Expr* in the AST twice.
14547 class ExprBuilder {
14548  ExprBuilder(const ExprBuilder&) = delete;
14549  ExprBuilder &operator=(const ExprBuilder&) = delete;
14550 
14551 protected:
14552  static Expr *assertNotNull(Expr *E) {
14553  assert(E && "Expression construction must not fail.");
14554  return E;
14555  }
14556 
14557 public:
14558  ExprBuilder() {}
14559  virtual ~ExprBuilder() {}
14560 
14561  virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14562 };
14563 
14564 class RefBuilder: public ExprBuilder {
14565  VarDecl *Var;
14566  QualType VarType;
14567 
14568 public:
14569  Expr *build(Sema &S, SourceLocation Loc) const override {
14570  return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
14571  }
14572 
14573  RefBuilder(VarDecl *Var, QualType VarType)
14574  : Var(Var), VarType(VarType) {}
14575 };
14576 
14577 class ThisBuilder: public ExprBuilder {
14578 public:
14579  Expr *build(Sema &S, SourceLocation Loc) const override {
14580  return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
14581  }
14582 };
14583 
14584 class CastBuilder: public ExprBuilder {
14585  const ExprBuilder &Builder;
14586  QualType Type;
14588  const CXXCastPath &Path;
14589 
14590 public:
14591  Expr *build(Sema &S, SourceLocation Loc) const override {
14592  return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
14593  CK_UncheckedDerivedToBase, Kind,
14594  &Path).get());
14595  }
14596 
14597  CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14598  const CXXCastPath &Path)
14599  : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14600 };
14601 
14602 class DerefBuilder: public ExprBuilder {
14603  const ExprBuilder &Builder;
14604 
14605 public:
14606  Expr *build(Sema &S, SourceLocation Loc) const override {
14607  return assertNotNull(
14608  S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
14609  }
14610 
14611  DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14612 };
14613 
14614 class MemberBuilder: public ExprBuilder {
14615  const ExprBuilder &Builder;
14616  QualType Type;
14617  CXXScopeSpec SS;
14618  bool IsArrow;
14619  LookupResult &MemberLookup;
14620 
14621 public:
14622  Expr *build(Sema &S, SourceLocation Loc) const override {
14623  return assertNotNull(S.BuildMemberReferenceExpr(
14624  Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
14625  nullptr, MemberLookup, nullptr, nullptr).get());
14626  }
14627 
14628  MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14629  LookupResult &MemberLookup)
14630  : Builder(Builder), Type(Type), IsArrow(IsArrow),
14631  MemberLookup(MemberLookup) {}
14632 };
14633 
14634 class MoveCastBuilder: public ExprBuilder {
14635  const ExprBuilder &Builder;
14636 
14637 public:
14638  Expr *build(Sema &S, SourceLocation Loc) const override {
14639  return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
14640  }
14641 
14642  MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14643 };
14644 
14645 class LvalueConvBuilder: public ExprBuilder {
14646  const ExprBuilder &Builder;
14647 
14648 public:
14649  Expr *build(Sema &S, SourceLocation Loc) const override {
14650  return assertNotNull(
14651  S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14652  }
14653 
14654  LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14655 };
14656 
14657 class SubscriptBuilder: public ExprBuilder {
14658  const ExprBuilder &Base;
14659  const ExprBuilder &Index;
14660 
14661 public:
14662  Expr *build(Sema &S, SourceLocation Loc) const override {
14663  return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14664  Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14665  }
14666 
14667  SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14668  : Base(Base), Index(Index) {}
14669 };
14670 
14671 } // end anonymous namespace
14672 
14673 /// When generating a defaulted copy or move assignment operator, if a field
14674 /// should be copied with __builtin_memcpy rather than via explicit assignments,
14675 /// do so. This optimization only applies for arrays of scalars, and for arrays
14676 /// of class type where the selected copy/move-assignment operator is trivial.
14677 static StmtResult
14679  const ExprBuilder &ToB, const ExprBuilder &FromB) {
14680  // Compute the size of the memory buffer to be copied.
14681  QualType SizeType = S.Context.getSizeType();
14682  llvm::APInt Size(S.Context.getTypeSize(SizeType),
14684 
14685  // Take the address of the field references for "from" and "to". We
14686  // directly construct UnaryOperators here because semantic analysis
14687  // does not permit us to take the address of an xvalue.
14688  Expr *From = FromB.build(S, Loc);
14689  From = UnaryOperator::Create(
14690  S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14691  VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14692  Expr *To = ToB.build(S, Loc);
14693  To = UnaryOperator::Create(
14694  S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14695  VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14696 
14697  const Type *E = T->getBaseElementTypeUnsafe();
14698  bool NeedsCollectableMemCpy =
14699  E->isRecordType() &&
14700  E->castAs<RecordType>()->getDecl()->hasObjectMember();
14701 
14702  // Create a reference to the __builtin_objc_memmove_collectable function
14703  StringRef MemCpyName = NeedsCollectableMemCpy ?
14704  "__builtin_objc_memmove_collectable" :
14705  "__builtin_memcpy";
14706  LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14708  S.LookupName(R, S.TUScope, true);
14709 
14710  FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14711  if (!MemCpy)
14712  // Something went horribly wrong earlier, and we will have complained
14713  // about it.
14714  return StmtError();
14715 
14716  ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14717  VK_PRValue, Loc, nullptr);
14718  assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14719 
14720  Expr *CallArgs[] = {
14721  To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14722  };
14723  ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14724  Loc, CallArgs, Loc);
14725 
14726  assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14727  return Call.getAs<Stmt>();
14728 }
14729 
14730 /// Builds a statement that copies/moves the given entity from \p From to
14731 /// \c To.
14732 ///
14733 /// This routine is used to copy/move the members of a class with an
14734 /// implicitly-declared copy/move assignment operator. When the entities being
14735 /// copied are arrays, this routine builds for loops to copy them.
14736 ///
14737 /// \param S The Sema object used for type-checking.
14738 ///
14739 /// \param Loc The location where the implicit copy/move is being generated.
14740 ///
14741 /// \param T The type of the expressions being copied/moved. Both expressions
14742 /// must have this type.
14743 ///
14744 /// \param To The expression we are copying/moving to.
14745 ///
14746 /// \param From The expression we are copying/moving from.
14747 ///
14748 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14749 /// Otherwise, it's a non-static member subobject.
14750 ///
14751 /// \param Copying Whether we're copying or moving.
14752 ///
14753 /// \param Depth Internal parameter recording the depth of the recursion.
14754 ///
14755 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14756 /// if a memcpy should be used instead.
14757 static StmtResult
14759  const ExprBuilder &To, const ExprBuilder &From,
14760  bool CopyingBaseSubobject, bool Copying,
14761  unsigned Depth = 0) {
14762  // C++11 [class.copy]p28:
14763  // Each subobject is assigned in the manner appropriate to its type:
14764  //
14765  // - if the subobject is of class type, as if by a call to operator= with
14766  // the subobject as the object expression and the corresponding
14767  // subobject of x as a single function argument (as if by explicit
14768  // qualification; that is, ignoring any possible virtual overriding
14769  // functions in more derived classes);
14770  //
14771  // C++03 [class.copy]p13:
14772  // - if the subobject is of class type, the copy assignment operator for
14773  // the class is used (as if by explicit qualification; that is,
14774  // ignoring any possible virtual overriding functions in more derived
14775  // classes);
14776  if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14777  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
14778 
14779  // Look for operator=.
14780  DeclarationName Name
14782  LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14783  S.LookupQualifiedName(OpLookup, ClassDecl, false);
14784 
14785  // Prior to C++11, filter out any result that isn't a copy/move-assignment
14786  // operator.
14787  if (!S.getLangOpts().CPlusPlus11) {
14788  LookupResult::Filter F = OpLookup.makeFilter();
14789  while (F.hasNext()) {
14790  NamedDecl *D = F.next();
14791  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14792  if (Method->isCopyAssignmentOperator() ||
14793  (!Copying && Method->isMoveAssignmentOperator()))
14794  continue;
14795 
14796  F.erase();
14797  }
14798  F.done();
14799  }
14800 
14801  // Suppress the protected check (C++ [class.protected]) for each of the
14802  // assignment operators we found. This strange dance is required when
14803  // we're assigning via a base classes's copy-assignment operator. To
14804  // ensure that we're getting the right base class subobject (without
14805  // ambiguities), we need to cast "this" to that subobject type; to
14806  // ensure that we don't go through the virtual call mechanism, we need
14807  // to qualify the operator= name with the base class (see below). However,
14808  // this means that if the base class has a protected copy assignment
14809  // operator, the protected member access check will fail. So, we
14810  // rewrite "protected" access to "public" access in this case, since we
14811  // know by construction that we're calling from a derived class.
14812  if (CopyingBaseSubobject) {
14813  for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14814  L != LEnd; ++L) {
14815  if (L.getAccess() == AS_protected)
14816  L.setAccess(AS_public);
14817  }
14818  }
14819 
14820  // Create the nested-name-specifier that will be used to qualify the
14821  // reference to operator=; this is required to suppress the virtual
14822  // call mechanism.
14823  CXXScopeSpec SS;
14824  const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14825  SS.MakeTrivial(S.Context,
14826  NestedNameSpecifier::Create(S.Context, nullptr, false,
14827  CanonicalT),
14828  Loc);
14829 
14830  // Create the reference to operator=.
14831  ExprResult OpEqualRef
14832  = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14833  SS, /*TemplateKWLoc=*/SourceLocation(),
14834  /*FirstQualifierInScope=*/nullptr,
14835  OpLookup,
14836  /*TemplateArgs=*/nullptr, /*S*/nullptr,
14837  /*SuppressQualifierCheck=*/true);
14838  if (OpEqualRef.isInvalid())
14839  return StmtError();
14840 
14841  // Build the call to the assignment operator.
14842 
14843  Expr *FromInst = From.build(S, Loc);
14844  ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14845  OpEqualRef.getAs<Expr>(),
14846  Loc, FromInst, Loc);
14847  if (Call.isInvalid())
14848  return StmtError();
14849 
14850  // If we built a call to a trivial 'operator=' while copying an array,
14851  // bail out. We'll replace the whole shebang with a memcpy.
14852  CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14853  if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14854  return StmtResult((Stmt*)nullptr);
14855 
14856  // Convert to an expression-statement, and clean up any produced
14857  // temporaries.
14858  return S.ActOnExprStmt(Call);
14859  }
14860 
14861  // - if the subobject is of scalar type, the built-in assignment
14862  // operator is used.
14863  const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
14864  if (!ArrayTy) {
14866  Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14867  if (Assignment.isInvalid())
14868  return StmtError();
14869  return S.ActOnExprStmt(Assignment);
14870  }
14871 
14872  // - if the subobject is an array, each element is assigned, in the
14873  // manner appropriate to the element type;
14874 
14875  // Construct a loop over the array bounds, e.g.,
14876  //
14877  // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14878  //
14879  // that will copy each of the array elements.
14880  QualType SizeType = S.Context.getSizeType();
14881 
14882  // Create the iteration variable.
14883  IdentifierInfo *IterationVarName = nullptr;
14884  {
14885  SmallString<8> Str;
14886  llvm::raw_svector_ostream OS(Str);
14887  OS << "__i" << Depth;
14888  IterationVarName = &S.Context.Idents.get(OS.str());
14889  }
14890  VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14891  IterationVarName, SizeType,
14892  S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
14893  SC_None);
14894 
14895  // Initialize the iteration variable to zero.
14896  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14897  IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14898 
14899  // Creates a reference to the iteration variable.
14900  RefBuilder IterationVarRef(IterationVar, SizeType);
14901  LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14902 
14903  // Create the DeclStmt that holds the iteration variable.
14904  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14905 
14906  // Subscript the "from" and "to" expressions with the iteration variable.
14907  SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14908  MoveCastBuilder FromIndexMove(FromIndexCopy);
14909  const ExprBuilder *FromIndex;
14910  if (Copying)
14911  FromIndex = &FromIndexCopy;
14912  else
14913  FromIndex = &FromIndexMove;
14914 
14915  SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14916 
14917  // Build the copy/move for an individual element of the array.
14918  StmtResult Copy =
14920  ToIndex, *FromIndex, CopyingBaseSubobject,
14921  Copying, Depth + 1);
14922  // Bail out if copying fails or if we determined that we should use memcpy.
14923  if (Copy.isInvalid() || !Copy.get())
14924  return Copy;
14925 
14926  // Create the comparison against the array bound.
14927  llvm::APInt Upper
14928  = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14929  Expr *Comparison = BinaryOperator::Create(
14930  S.Context, IterationVarRefRVal.build(S, Loc),
14931  IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14933  S.CurFPFeatureOverrides());
14934 
14935  // Create the pre-increment of the iteration variable. We can determine
14936  // whether the increment will overflow based on the value of the array
14937  // bound.
14938  Expr *Increment = UnaryOperator::Create(
14939  S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
14940  OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
14941 
14942  // Construct the loop that copies all elements of this array.
14943  return S.ActOnForStmt(
14944  Loc, Loc, InitStmt,
14945  S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
14946  S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
14947 }
14948 
14949 static StmtResult
14951  const ExprBuilder &To, const ExprBuilder &From,
14952  bool CopyingBaseSubobject, bool Copying) {
14953  // Maybe we should use a memcpy?
14954  if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14955  T.isTriviallyCopyableType(S.Context))
14956  return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14957 
14958  StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
14959  CopyingBaseSubobject,
14960  Copying, 0));
14961 
14962  // If we ended up picking a trivial assignment operator for an array of a
14963  // non-trivially-copyable class type, just emit a memcpy.
14964  if (!Result.isInvalid() && !Result.get())
14965  return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14966 
14967  return Result;
14968 }
14969 
14971  // Note: The following rules are largely analoguous to the copy
14972  // constructor rules. Note that virtual bases are not taken into account
14973  // for determining the argument type of the operator. Note also that
14974  // operators taking an object instead of a reference are allowed.
14975  assert(ClassDecl->needsImplicitCopyAssignment());
14976 
14977  DeclaringSpecialMember DSM(*this, ClassDecl,
14979  if (DSM.isAlreadyBeingDeclared())
14980  return nullptr;
14981 
14982  QualType ArgType = Context.getTypeDeclType(ClassDecl);
14984  ArgType, nullptr);
14986  if (AS != LangAS::Default)
14987  ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14988  QualType RetType = Context.getLValueReferenceType(ArgType);
14989  bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14990  if (Const)
14991  ArgType = ArgType.withConst();
14992 
14993  ArgType = Context.getLValueReferenceType(ArgType);
14994 
14996  *this, ClassDecl, CXXSpecialMemberKind::CopyAssignment, Const);
14997 
14998  // An implicitly-declared copy assignment operator is an inline public
14999  // member of its class.
15001  SourceLocation ClassLoc = ClassDecl->getLocation();
15002  DeclarationNameInfo NameInfo(Name, ClassLoc);
15004  Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15005  /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15006  getCurFPFeatures().isFPConstrained(),
15007  /*isInline=*/true,
15009  SourceLocation());
15010  CopyAssignment->setAccess(AS_public);
15011  CopyAssignment->setDefaulted();
15012  CopyAssignment->setImplicit();
15013 
15014  setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
15015 
15016  if (getLangOpts().CUDA)
15019  /* ConstRHS */ Const,
15020  /* Diagnose */ false);
15021 
15022  // Add the parameter to the operator.
15024  ClassLoc, ClassLoc,
15025  /*Id=*/nullptr, ArgType,
15026  /*TInfo=*/nullptr, SC_None,
15027  nullptr);
15028  CopyAssignment->setParams(FromParam);
15029 
15030  CopyAssignment->setTrivial(
15034  : ClassDecl->hasTrivialCopyAssignment());
15035 
15036  // Note that we have added this copy-assignment operator.
15038 
15039  Scope *S = getScopeForContext(ClassDecl);
15041 
15045  SetDeclDeleted(CopyAssignment, ClassLoc);
15046  }
15047 
15048  if (S)
15049  PushOnScopeChains(CopyAssignment, S, false);
15050  ClassDecl->addDecl(CopyAssignment);
15051 
15052  return CopyAssignment;
15053 }
15054 
15055 /// Diagnose an implicit copy operation for a class which is odr-used, but
15056 /// which is deprecated because the class has a user-declared copy constructor,
15057 /// copy assignment operator, or destructor.
15059  assert(CopyOp->isImplicit());
15060 
15061  CXXRecordDecl *RD = CopyOp->getParent();
15062  CXXMethodDecl *UserDeclaredOperation = nullptr;
15063 
15064  if (RD->hasUserDeclaredDestructor()) {
15065  UserDeclaredOperation = RD->getDestructor();
15066  } else if (!isa<CXXConstructorDecl>(CopyOp) &&
15068  // Find any user-declared copy constructor.
15069  for (auto *I : RD->ctors()) {
15070  if (I->isCopyConstructor()) {
15071  UserDeclaredOperation = I;
15072  break;
15073  }
15074  }
15075  assert(UserDeclaredOperation);
15076  } else if (isa<CXXConstructorDecl>(CopyOp) &&
15078  // Find any user-declared move assignment operator.
15079  for (auto *I : RD->methods()) {
15080  if (I->isCopyAssignmentOperator()) {
15081  UserDeclaredOperation = I;
15082  break;
15083  }
15084  }
15085  assert(UserDeclaredOperation);
15086  }
15087 
15088  if (UserDeclaredOperation) {
15089  bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
15090  bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
15091  bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
15092  unsigned DiagID =
15093  (UDOIsUserProvided && UDOIsDestructor)
15094  ? diag::warn_deprecated_copy_with_user_provided_dtor
15095  : (UDOIsUserProvided && !UDOIsDestructor)
15096  ? diag::warn_deprecated_copy_with_user_provided_copy
15097  : (!UDOIsUserProvided && UDOIsDestructor)
15098  ? diag::warn_deprecated_copy_with_dtor
15099  : diag::warn_deprecated_copy;
15100  S.Diag(UserDeclaredOperation->getLocation(), DiagID)
15101  << RD << IsCopyAssignment;
15102  }
15103 }
15104 
15106  CXXMethodDecl *CopyAssignOperator) {
15107  assert((CopyAssignOperator->isDefaulted() &&
15108  CopyAssignOperator->isOverloadedOperator() &&
15109  CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
15110  !CopyAssignOperator->doesThisDeclarationHaveABody() &&
15111  !CopyAssignOperator->isDeleted()) &&
15112  "DefineImplicitCopyAssignment called for wrong function");
15113  if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
15114  return;
15115 
15116  CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
15117  if (ClassDecl->isInvalidDecl()) {
15118  CopyAssignOperator->setInvalidDecl();
15119  return;
15120  }
15121 
15122  SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
15123 
15124  // The exception specification is needed because we are defining the
15125  // function.
15126  ResolveExceptionSpec(CurrentLocation,
15127  CopyAssignOperator->getType()->castAs<FunctionProtoType>());
15128 
15129  // Add a context note for diagnostics produced after this point.
15130  Scope.addContextNote(CurrentLocation);
15131 
15132  // C++11 [class.copy]p18:
15133  // The [definition of an implicitly declared copy assignment operator] is
15134  // deprecated if the class has a user-declared copy constructor or a
15135  // user-declared destructor.
15136  if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
15137  diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
15138 
15139  // C++0x [class.copy]p30:
15140  // The implicitly-defined or explicitly-defaulted copy assignment operator
15141  // for a non-union class X performs memberwise copy assignment of its
15142  // subobjects. The direct base classes of X are assigned first, in the
15143  // order of their declaration in the base-specifier-list, and then the
15144  // immediate non-static data members of X are assigned, in the order in
15145  // which they were declared in the class definition.
15146 
15147  // The statements that form the synthesized function body.
15148  SmallVector<Stmt*, 8> Statements;
15149 
15150  // The parameter for the "other" object, which we are copying from.
15151  ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(0);
15152  Qualifiers OtherQuals = Other->getType().getQualifiers();
15153  QualType OtherRefType = Other->getType();
15154  if (OtherRefType->isLValueReferenceType()) {
15155  OtherRefType = OtherRefType->getPointeeType();
15156  OtherQuals = OtherRefType.getQualifiers();
15157  }
15158 
15159  // Our location for everything implicitly-generated.
15160  SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
15161  ? CopyAssignOperator->getEndLoc()
15162  : CopyAssignOperator->getLocation();
15163 
15164  // Builds a DeclRefExpr for the "other" object.
15165  RefBuilder OtherRef(Other, OtherRefType);
15166 
15167  // Builds the function object parameter.
15168  std::optional<ThisBuilder> This;
15169  std::optional<DerefBuilder> DerefThis;
15170  std::optional<RefBuilder> ExplicitObject;
15171  bool IsArrow = false;
15172  QualType ObjectType;
15173  if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
15174  ObjectType = CopyAssignOperator->getParamDecl(0)->getType();
15175  if (ObjectType->isReferenceType())
15176  ObjectType = ObjectType->getPointeeType();
15177  ExplicitObject.emplace(CopyAssignOperator->getParamDecl(0), ObjectType);
15178  } else {
15179  ObjectType = getCurrentThisType();
15180  This.emplace();
15181  DerefThis.emplace(*This);
15182  IsArrow = !LangOpts.HLSL;
15183  }
15184  ExprBuilder &ObjectParameter =
15185  ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15186  : static_cast<ExprBuilder &>(*This);
15187 
15188  // Assign base classes.
15189  bool Invalid = false;
15190  for (auto &Base : ClassDecl->bases()) {
15191  // Form the assignment:
15192  // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15193  QualType BaseType = Base.getType().getUnqualifiedType();
15194  if (!BaseType->isRecordType()) {
15195  Invalid = true;
15196  continue;
15197  }
15198 
15199  CXXCastPath BasePath;
15200  BasePath.push_back(&Base);
15201 
15202  // Construct the "from" expression, which is an implicit cast to the
15203  // appropriately-qualified base type.
15204  CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
15205  VK_LValue, BasePath);
15206 
15207  // Dereference "this".
15208  CastBuilder To(
15209  ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15210  : static_cast<ExprBuilder &>(*DerefThis),
15211  Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15212  VK_LValue, BasePath);
15213 
15214  // Build the copy.
15215  StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
15216  To, From,
15217  /*CopyingBaseSubobject=*/true,
15218  /*Copying=*/true);
15219  if (Copy.isInvalid()) {
15220  CopyAssignOperator->setInvalidDecl();
15221  return;
15222  }
15223 
15224  // Success! Record the copy.
15225  Statements.push_back(Copy.getAs<Expr>());
15226  }
15227 
15228  // Assign non-static members.
15229  for (auto *Field : ClassDecl->fields()) {
15230  // FIXME: We should form some kind of AST representation for the implied
15231  // memcpy in a union copy operation.
15232  if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15233  continue;
15234 
15235  if (Field->isInvalidDecl()) {
15236  Invalid = true;
15237  continue;
15238  }
15239 
15240  // Check for members of reference type; we can't copy those.
15241  if (Field->getType()->isReferenceType()) {
15242  Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15243  << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15244  Diag(Field->getLocation(), diag::note_declared_at);
15245  Invalid = true;
15246  continue;
15247  }
15248 
15249  // Check for members of const-qualified, non-class type.
15250  QualType BaseType = Context.getBaseElementType(Field->getType());
15251  if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15252  Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15253  << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15254  Diag(Field->getLocation(), diag::note_declared_at);
15255  Invalid = true;
15256  continue;
15257  }
15258 
15259  // Suppress assigning zero-width bitfields.
15260  if (Field->isZeroLengthBitField(Context))
15261  continue;
15262 
15263  QualType FieldType = Field->getType().getNonReferenceType();
15264  if (FieldType->isIncompleteArrayType()) {
15265  assert(ClassDecl->hasFlexibleArrayMember() &&
15266  "Incomplete array type is not valid");
15267  continue;
15268  }
15269 
15270  // Build references to the field in the object we're copying from and to.
15271  CXXScopeSpec SS; // Intentionally empty
15272  LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15274  MemberLookup.addDecl(Field);
15275  MemberLookup.resolveKind();
15276 
15277  MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15278  MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15279  // Build the copy of this field.
15280  StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
15281  To, From,
15282  /*CopyingBaseSubobject=*/false,
15283  /*Copying=*/true);
15284  if (Copy.isInvalid()) {
15285  CopyAssignOperator->setInvalidDecl();
15286  return;
15287  }
15288 
15289  // Success! Record the copy.
15290  Statements.push_back(Copy.getAs<Stmt>());
15291  }
15292 
15293  if (!Invalid) {
15294  // Add a "return *this;"
15295  Expr *ThisExpr =
15296  (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15297  : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15298  : static_cast<ExprBuilder &>(*DerefThis))
15299  .build(*this, Loc);
15300  StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15301  if (Return.isInvalid())
15302  Invalid = true;
15303  else
15304  Statements.push_back(Return.getAs<Stmt>());
15305  }
15306 
15307  if (Invalid) {
15308  CopyAssignOperator->setInvalidDecl();
15309  return;
15310  }
15311 
15312  StmtResult Body;
15313  {
15314  CompoundScopeRAII CompoundScope(*this);
15315  Body = ActOnCompoundStmt(Loc, Loc, Statements,
15316  /*isStmtExpr=*/false);
15317  assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15318  }
15319  CopyAssignOperator->setBody(Body.getAs<Stmt>());
15320  CopyAssignOperator->markUsed(Context);
15321 
15323  L->CompletedImplicitDefinition(CopyAssignOperator);
15324  }
15325 }
15326 
15328  assert(ClassDecl->needsImplicitMoveAssignment());
15329 
15330  DeclaringSpecialMember DSM(*this, ClassDecl,
15332  if (DSM.isAlreadyBeingDeclared())
15333  return nullptr;
15334 
15335  // Note: The following rules are largely analoguous to the move
15336  // constructor rules.
15337 
15338  QualType ArgType = Context.getTypeDeclType(ClassDecl);
15340  ArgType, nullptr);
15342  if (AS != LangAS::Default)
15343  ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15344  QualType RetType = Context.getLValueReferenceType(ArgType);
15345  ArgType = Context.getRValueReferenceType(ArgType);
15346 
15348  *this, ClassDecl, CXXSpecialMemberKind::MoveAssignment, false);
15349 
15350  // An implicitly-declared move assignment operator is an inline public
15351  // member of its class.
15353  SourceLocation ClassLoc = ClassDecl->getLocation();
15354  DeclarationNameInfo NameInfo(Name, ClassLoc);
15356  Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15357  /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15358  getCurFPFeatures().isFPConstrained(),
15359  /*isInline=*/true,
15361  SourceLocation());
15362  MoveAssignment->setAccess(AS_public);
15363  MoveAssignment->setDefaulted();
15364  MoveAssignment->setImplicit();
15365 
15366  setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
15367 
15368  if (getLangOpts().CUDA)
15371  /* ConstRHS */ false,
15372  /* Diagnose */ false);
15373 
15374  // Add the parameter to the operator.
15376  ClassLoc, ClassLoc,
15377  /*Id=*/nullptr, ArgType,
15378  /*TInfo=*/nullptr, SC_None,
15379  nullptr);
15380  MoveAssignment->setParams(FromParam);
15381 
15382  MoveAssignment->setTrivial(
15386  : ClassDecl->hasTrivialMoveAssignment());
15387 
15388  // Note that we have added this copy-assignment operator.
15390 
15391  Scope *S = getScopeForContext(ClassDecl);
15393 
15397  SetDeclDeleted(MoveAssignment, ClassLoc);
15398  }
15399 
15400  if (S)
15401  PushOnScopeChains(MoveAssignment, S, false);
15402  ClassDecl->addDecl(MoveAssignment);
15403 
15404  return MoveAssignment;
15405 }
15406 
15407 /// Check if we're implicitly defining a move assignment operator for a class
15408 /// with virtual bases. Such a move assignment might move-assign the virtual
15409 /// base multiple times.
15411  SourceLocation CurrentLocation) {
15412  assert(!Class->isDependentContext() && "should not define dependent move");
15413 
15414  // Only a virtual base could get implicitly move-assigned multiple times.
15415  // Only a non-trivial move assignment can observe this. We only want to
15416  // diagnose if we implicitly define an assignment operator that assigns
15417  // two base classes, both of which move-assign the same virtual base.
15418  if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15419  Class->getNumBases() < 2)
15420  return;
15421 
15423  typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15424  VBaseMap VBases;
15425 
15426  for (auto &BI : Class->bases()) {
15427  Worklist.push_back(&BI);
15428  while (!Worklist.empty()) {
15429  CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15430  CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15431 
15432  // If the base has no non-trivial move assignment operators,
15433  // we don't care about moves from it.
15434  if (!Base->hasNonTrivialMoveAssignment())
15435  continue;
15436 
15437  // If there's nothing virtual here, skip it.
15438  if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15439  continue;
15440 
15441  // If we're not actually going to call a move assignment for this base,
15442  // or the selected move assignment is trivial, skip it.
15445  /*ConstArg*/ false, /*VolatileArg*/ false,
15446  /*RValueThis*/ true, /*ConstThis*/ false,
15447  /*VolatileThis*/ false);
15448  if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15450  continue;
15451 
15452  if (BaseSpec->isVirtual()) {
15453  // We're going to move-assign this virtual base, and its move
15454  // assignment operator is not trivial. If this can happen for
15455  // multiple distinct direct bases of Class, diagnose it. (If it
15456  // only happens in one base, we'll diagnose it when synthesizing
15457  // that base class's move assignment operator.)
15458  CXXBaseSpecifier *&Existing =
15459  VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
15460  .first->second;
15461  if (Existing && Existing != &BI) {
15462  S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
15463  << Class << Base;
15464  S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
15465  << (Base->getCanonicalDecl() ==
15466  Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15467  << Base << Existing->getType() << Existing->getSourceRange();
15468  S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
15469  << (Base->getCanonicalDecl() ==
15470  BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15471  << Base << BI.getType() << BaseSpec->getSourceRange();
15472 
15473  // Only diagnose each vbase once.
15474  Existing = nullptr;
15475  }
15476  } else {
15477  // Only walk over bases that have defaulted move assignment operators.
15478  // We assume that any user-provided move assignment operator handles
15479  // the multiple-moves-of-vbase case itself somehow.
15480  if (!SMOR.getMethod()->isDefaulted())
15481  continue;
15482 
15483  // We're going to move the base classes of Base. Add them to the list.
15484  llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
15485  }
15486  }
15487  }
15488 }
15489 
15491  CXXMethodDecl *MoveAssignOperator) {
15492  assert((MoveAssignOperator->isDefaulted() &&
15493  MoveAssignOperator->isOverloadedOperator() &&
15494  MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15495  !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15496  !MoveAssignOperator->isDeleted()) &&
15497  "DefineImplicitMoveAssignment called for wrong function");
15498  if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15499  return;
15500 
15501  CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15502  if (ClassDecl->isInvalidDecl()) {
15503  MoveAssignOperator->setInvalidDecl();
15504  return;
15505  }
15506 
15507  // C++0x [class.copy]p28:
15508  // The implicitly-defined or move assignment operator for a non-union class
15509  // X performs memberwise move assignment of its subobjects. The direct base
15510  // classes of X are assigned first, in the order of their declaration in the
15511  // base-specifier-list, and then the immediate non-static data members of X
15512  // are assigned, in the order in which they were declared in the class
15513  // definition.
15514 
15515  // Issue a warning if our implicit move assignment operator will move
15516  // from a virtual base more than once.
15517  checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
15518 
15519  SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15520 
15521  // The exception specification is needed because we are defining the
15522  // function.
15523  ResolveExceptionSpec(CurrentLocation,
15524  MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15525 
15526  // Add a context note for diagnostics produced after this point.
15527  Scope.addContextNote(CurrentLocation);
15528 
15529  // The statements that form the synthesized function body.
15530  SmallVector<Stmt*, 8> Statements;
15531 
15532  // The parameter for the "other" object, which we are move from.
15533  ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(0);
15534  QualType OtherRefType =
15535  Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15536 
15537  // Our location for everything implicitly-generated.
15538  SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15539  ? MoveAssignOperator->getEndLoc()
15540  : MoveAssignOperator->getLocation();
15541 
15542  // Builds a reference to the "other" object.
15543  RefBuilder OtherRef(Other, OtherRefType);
15544  // Cast to rvalue.
15545  MoveCastBuilder MoveOther(OtherRef);
15546 
15547  // Builds the function object parameter.
15548  std::optional<ThisBuilder> This;
15549  std::optional<DerefBuilder> DerefThis;
15550  std::optional<RefBuilder> ExplicitObject;
15551  QualType ObjectType;
15552  if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15553  ObjectType = MoveAssignOperator->getParamDecl(0)->getType();
15554  if (ObjectType->isReferenceType())
15555  ObjectType = ObjectType->getPointeeType();
15556  ExplicitObject.emplace(MoveAssignOperator->getParamDecl(0), ObjectType);
15557  } else {
15558  ObjectType = getCurrentThisType();
15559  This.emplace();
15560  DerefThis.emplace(*This);
15561  }
15562  ExprBuilder &ObjectParameter =
15563  ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15564 
15565  // Assign base classes.
15566  bool Invalid = false;
15567  for (auto &Base : ClassDecl->bases()) {
15568  // C++11 [class.copy]p28:
15569  // It is unspecified whether subobjects representing virtual base classes
15570  // are assigned more than once by the implicitly-defined copy assignment
15571  // operator.
15572  // FIXME: Do not assign to a vbase that will be assigned by some other base
15573  // class. For a move-assignment, this can result in the vbase being moved
15574  // multiple times.
15575 
15576  // Form the assignment:
15577  // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15578  QualType BaseType = Base.getType().getUnqualifiedType();
15579  if (!BaseType->isRecordType()) {
15580  Invalid = true;
15581  continue;
15582  }
15583 
15584  CXXCastPath BasePath;
15585  BasePath.push_back(&Base);
15586 
15587  // Construct the "from" expression, which is an implicit cast to the
15588  // appropriately-qualified base type.
15589  CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15590 
15591  // Implicitly cast "this" to the appropriately-qualified base type.
15592  // Dereference "this".
15593  CastBuilder To(
15594  ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15595  : static_cast<ExprBuilder &>(*DerefThis),
15596  Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15597  VK_LValue, BasePath);
15598 
15599  // Build the move.
15600  StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
15601  To, From,
15602  /*CopyingBaseSubobject=*/true,
15603  /*Copying=*/false);
15604  if (Move.isInvalid()) {
15605  MoveAssignOperator->setInvalidDecl();
15606  return;
15607  }
15608 
15609  // Success! Record the move.
15610  Statements.push_back(Move.getAs<Expr>());
15611  }
15612 
15613  // Assign non-static members.
15614  for (auto *Field : ClassDecl->fields()) {
15615  // FIXME: We should form some kind of AST representation for the implied
15616  // memcpy in a union copy operation.
15617  if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15618  continue;
15619 
15620  if (Field->isInvalidDecl()) {
15621  Invalid = true;
15622  continue;
15623  }
15624 
15625  // Check for members of reference type; we can't move those.
15626  if (Field->getType()->isReferenceType()) {
15627  Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15628  << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15629  Diag(Field->getLocation(), diag::note_declared_at);
15630  Invalid = true;
15631  continue;
15632  }
15633 
15634  // Check for members of const-qualified, non-class type.
15635  QualType BaseType = Context.getBaseElementType(Field->getType());
15636  if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15637  Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15638  << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15639  Diag(Field->getLocation(), diag::note_declared_at);
15640  Invalid = true;
15641  continue;
15642  }
15643 
15644  // Suppress assigning zero-width bitfields.
15645  if (Field->isZeroLengthBitField(Context))
15646  continue;
15647 
15648  QualType FieldType = Field->getType().getNonReferenceType();
15649  if (FieldType->isIncompleteArrayType()) {
15650  assert(ClassDecl->hasFlexibleArrayMember() &&
15651  "Incomplete array type is not valid");
15652  continue;
15653  }
15654 
15655  // Build references to the field in the object we're copying from and to.
15656  LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15658  MemberLookup.addDecl(Field);
15659  MemberLookup.resolveKind();
15660  MemberBuilder From(MoveOther, OtherRefType,
15661  /*IsArrow=*/false, MemberLookup);
15662  MemberBuilder To(ObjectParameter, ObjectType, /*IsArrow=*/!ExplicitObject,
15663  MemberLookup);
15664 
15665  assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15666  "Member reference with rvalue base must be rvalue except for reference "
15667  "members, which aren't allowed for move assignment.");
15668 
15669  // Build the move of this field.
15670  StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
15671  To, From,
15672  /*CopyingBaseSubobject=*/false,
15673  /*Copying=*/false);
15674  if (Move.isInvalid()) {
15675  MoveAssignOperator->setInvalidDecl();
15676  return;
15677  }
15678 
15679  // Success! Record the copy.
15680  Statements.push_back(Move.getAs<Stmt>());
15681  }
15682 
15683  if (!Invalid) {
15684  // Add a "return *this;"
15685  Expr *ThisExpr =
15686  (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15687  : static_cast<ExprBuilder &>(*DerefThis))
15688  .build(*this, Loc);
15689 
15690  StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15691  if (Return.isInvalid())
15692  Invalid = true;
15693  else
15694  Statements.push_back(Return.getAs<Stmt>());
15695  }
15696 
15697  if (Invalid) {
15698  MoveAssignOperator->setInvalidDecl();
15699  return;
15700  }
15701 
15702  StmtResult Body;
15703  {
15704  CompoundScopeRAII CompoundScope(*this);
15705  Body = ActOnCompoundStmt(Loc, Loc, Statements,
15706  /*isStmtExpr=*/false);
15707  assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15708  }
15709  MoveAssignOperator->setBody(Body.getAs<Stmt>());
15710  MoveAssignOperator->markUsed(Context);
15711 
15713  L->CompletedImplicitDefinition(MoveAssignOperator);
15714  }
15715 }
15716 
15718  CXXRecordDecl *ClassDecl) {
15719  // C++ [class.copy]p4:
15720  // If the class definition does not explicitly declare a copy
15721  // constructor, one is declared implicitly.
15722  assert(ClassDecl->needsImplicitCopyConstructor());
15723 
15724  DeclaringSpecialMember DSM(*this, ClassDecl,
15726  if (DSM.isAlreadyBeingDeclared())
15727  return nullptr;
15728 
15729  QualType ClassType = Context.getTypeDeclType(ClassDecl);
15730  QualType ArgType = ClassType;
15732  ArgType, nullptr);
15733  bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15734  if (Const)
15735  ArgType = ArgType.withConst();
15736 
15738  if (AS != LangAS::Default)
15739  ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15740 
15741  ArgType = Context.getLValueReferenceType(ArgType);
15742 
15744  *this, ClassDecl, CXXSpecialMemberKind::CopyConstructor, Const);
15745 
15746  DeclarationName Name
15748  Context.getCanonicalType(ClassType));
15749  SourceLocation ClassLoc = ClassDecl->getLocation();
15750  DeclarationNameInfo NameInfo(Name, ClassLoc);
15751 
15752  // An implicitly-declared copy constructor is an inline public
15753  // member of its class.
15755  Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15756  ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15757  /*isInline=*/true,
15758  /*isImplicitlyDeclared=*/true,
15761  CopyConstructor->setAccess(AS_public);
15762  CopyConstructor->setDefaulted();
15763 
15764  setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
15765 
15766  if (getLangOpts().CUDA)
15769  /* ConstRHS */ Const,
15770  /* Diagnose */ false);
15771 
15772  // During template instantiation of special member functions we need a
15773  // reliable TypeSourceInfo for the parameter types in order to allow functions
15774  // to be substituted.
15775  TypeSourceInfo *TSI = nullptr;
15776  if (inTemplateInstantiation() && ClassDecl->isLambda())
15777  TSI = Context.getTrivialTypeSourceInfo(ArgType);
15778 
15779  // Add the parameter to the constructor.
15780  ParmVarDecl *FromParam =
15781  ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15782  /*IdentifierInfo=*/nullptr, ArgType,
15783  /*TInfo=*/TSI, SC_None, nullptr);
15784  CopyConstructor->setParams(FromParam);
15785 
15786  CopyConstructor->setTrivial(
15790  : ClassDecl->hasTrivialCopyConstructor());
15791 
15792  CopyConstructor->setTrivialForCall(
15793  ClassDecl->hasAttr<TrivialABIAttr>() ||
15798  : ClassDecl->hasTrivialCopyConstructorForCall()));
15799 
15800  // Note that we have declared this constructor.
15802 
15803  Scope *S = getScopeForContext(ClassDecl);
15805 
15809  SetDeclDeleted(CopyConstructor, ClassLoc);
15810  }
15811 
15812  if (S)
15814  ClassDecl->addDecl(CopyConstructor);
15815 
15816  return CopyConstructor;
15817 }
15818 
15820  CXXConstructorDecl *CopyConstructor) {
15821  assert((CopyConstructor->isDefaulted() &&
15822  CopyConstructor->isCopyConstructor() &&
15823  !CopyConstructor->doesThisDeclarationHaveABody() &&
15824  !CopyConstructor->isDeleted()) &&
15825  "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15826  if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15827  return;
15828 
15829  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15830  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15831 
15833 
15834  // The exception specification is needed because we are defining the
15835  // function.
15836  ResolveExceptionSpec(CurrentLocation,
15837  CopyConstructor->getType()->castAs<FunctionProtoType>());
15838  MarkVTableUsed(CurrentLocation, ClassDecl);
15839 
15840  // Add a context note for diagnostics produced after this point.
15841  Scope.addContextNote(CurrentLocation);
15842 
15843  // C++11 [class.copy]p7:
15844  // The [definition of an implicitly declared copy constructor] is
15845  // deprecated if the class has a user-declared copy assignment operator
15846  // or a user-declared destructor.
15847  if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15849 
15850  if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
15851  CopyConstructor->setInvalidDecl();
15852  } else {
15853  SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15854  ? CopyConstructor->getEndLoc()
15855  : CopyConstructor->getLocation();
15856  Sema::CompoundScopeRAII CompoundScope(*this);
15857  CopyConstructor->setBody(
15858  ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)
15859  .getAs<Stmt>());
15860  CopyConstructor->markUsed(Context);
15861  }
15862 
15864  L->CompletedImplicitDefinition(CopyConstructor);
15865  }
15866 }
15867 
15869  CXXRecordDecl *ClassDecl) {
15870  assert(ClassDecl->needsImplicitMoveConstructor());
15871 
15872  DeclaringSpecialMember DSM(*this, ClassDecl,
15874  if (DSM.isAlreadyBeingDeclared())
15875  return nullptr;
15876 
15877  QualType ClassType = Context.getTypeDeclType(ClassDecl);
15878 
15879  QualType ArgType = ClassType;
15881  ArgType, nullptr);
15883  if (AS != LangAS::Default)
15884  ArgType = Context.getAddrSpaceQualType(ClassType, AS);
15885  ArgType = Context.getRValueReferenceType(ArgType);
15886 
15888  *this, ClassDecl, CXXSpecialMemberKind::MoveConstructor, false);
15889 
15890  DeclarationName Name
15892  Context.getCanonicalType(ClassType));
15893  SourceLocation ClassLoc = ClassDecl->getLocation();
15894  DeclarationNameInfo NameInfo(Name, ClassLoc);
15895 
15896  // C++11 [class.copy]p11:
15897  // An implicitly-declared copy/move constructor is an inline public
15898  // member of its class.
15900  Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15901  ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15902  /*isInline=*/true,
15903  /*isImplicitlyDeclared=*/true,
15906  MoveConstructor->setAccess(AS_public);
15907  MoveConstructor->setDefaulted();
15908 
15909  setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15910 
15911  if (getLangOpts().CUDA)
15914  /* ConstRHS */ false,
15915  /* Diagnose */ false);
15916 
15917  // Add the parameter to the constructor.
15919  ClassLoc, ClassLoc,
15920  /*IdentifierInfo=*/nullptr,
15921  ArgType, /*TInfo=*/nullptr,
15922  SC_None, nullptr);
15923  MoveConstructor->setParams(FromParam);
15924 
15925  MoveConstructor->setTrivial(
15929  : ClassDecl->hasTrivialMoveConstructor());
15930 
15931  MoveConstructor->setTrivialForCall(
15932  ClassDecl->hasAttr<TrivialABIAttr>() ||
15937  : ClassDecl->hasTrivialMoveConstructorForCall()));
15938 
15939  // Note that we have declared this constructor.
15941 
15942  Scope *S = getScopeForContext(ClassDecl);
15944 
15948  SetDeclDeleted(MoveConstructor, ClassLoc);
15949  }
15950 
15951  if (S)
15953  ClassDecl->addDecl(MoveConstructor);
15954 
15955  return MoveConstructor;
15956 }
15957 
15959  CXXConstructorDecl *MoveConstructor) {
15960  assert((MoveConstructor->isDefaulted() &&
15961  MoveConstructor->isMoveConstructor() &&
15962  !MoveConstructor->doesThisDeclarationHaveABody() &&
15963  !MoveConstructor->isDeleted()) &&
15964  "DefineImplicitMoveConstructor - call it for implicit move ctor");
15965  if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15966  return;
15967 
15968  CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15969  assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
15970 
15972 
15973  // The exception specification is needed because we are defining the
15974  // function.
15975  ResolveExceptionSpec(CurrentLocation,
15976  MoveConstructor->getType()->castAs<FunctionProtoType>());
15977  MarkVTableUsed(CurrentLocation, ClassDecl);
15978 
15979  // Add a context note for diagnostics produced after this point.
15980  Scope.addContextNote(CurrentLocation);
15981 
15982  if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
15983  MoveConstructor->setInvalidDecl();
15984  } else {
15985  SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15986  ? MoveConstructor->getEndLoc()
15987  : MoveConstructor->getLocation();
15988  Sema::CompoundScopeRAII CompoundScope(*this);
15989  MoveConstructor->setBody(
15990  ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)
15991  .getAs<Stmt>());
15992  MoveConstructor->markUsed(Context);
15993  }
15994 
15996  L->CompletedImplicitDefinition(MoveConstructor);
15997  }
15998 }
15999 
16001  return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
16002 }
16003 
16005  SourceLocation CurrentLocation,
16006  CXXConversionDecl *Conv) {
16007  SynthesizedFunctionScope Scope(*this, Conv);
16008  assert(!Conv->getReturnType()->isUndeducedType());
16009 
16010  QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
16011  CallingConv CC =
16012  ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
16013 
16014  CXXRecordDecl *Lambda = Conv->getParent();
16015  FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
16016  FunctionDecl *Invoker =
16017  CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
16018  ? CallOp
16019  : Lambda->getLambdaStaticInvoker(CC);
16020 
16021  if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
16023  CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
16024  if (!CallOp)
16025  return;
16026 
16027  if (CallOp != Invoker) {
16029  Invoker->getDescribedFunctionTemplate(), TemplateArgs,
16030  CurrentLocation);
16031  if (!Invoker)
16032  return;
16033  }
16034  }
16035 
16036  if (CallOp->isInvalidDecl())
16037  return;
16038 
16039  // Mark the call operator referenced (and add to pending instantiations
16040  // if necessary).
16041  // For both the conversion and static-invoker template specializations
16042  // we construct their body's in this function, so no need to add them
16043  // to the PendingInstantiations.
16044  MarkFunctionReferenced(CurrentLocation, CallOp);
16045 
16046  if (Invoker != CallOp) {
16047  // Fill in the __invoke function with a dummy implementation. IR generation
16048  // will fill in the actual details. Update its type in case it contained
16049  // an 'auto'.
16050  Invoker->markUsed(Context);
16051  Invoker->setReferenced();
16052  Invoker->setType(Conv->getReturnType()->getPointeeType());
16053  Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
16054  }
16055 
16056  // Construct the body of the conversion function { return __invoke; }.
16057  Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
16058  Conv->getLocation());
16059  assert(FunctionRef && "Can't refer to __invoke function?");
16060  Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
16062  Conv->getLocation(), Conv->getLocation()));
16063  Conv->markUsed(Context);
16064  Conv->setReferenced();
16065 
16067  L->CompletedImplicitDefinition(Conv);
16068  if (Invoker != CallOp)
16069  L->CompletedImplicitDefinition(Invoker);
16070  }
16071 }
16072 
16074  SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
16075  assert(!Conv->getParent()->isGenericLambda());
16076 
16077  SynthesizedFunctionScope Scope(*this, Conv);
16078 
16079  // Copy-initialize the lambda object as needed to capture it.
16080  Expr *This = ActOnCXXThis(CurrentLocation).get();
16081  Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
16082 
16083  ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
16084  Conv->getLocation(),
16085  Conv, DerefThis);
16086 
16087  // If we're not under ARC, make sure we still get the _Block_copy/autorelease
16088  // behavior. Note that only the general conversion function does this
16089  // (since it's unusable otherwise); in the case where we inline the
16090  // block literal, it has block literal lifetime semantics.
16091  if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
16092  BuildBlock = ImplicitCastExpr::Create(
16093  Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
16094  BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
16095 
16096  if (BuildBlock.isInvalid()) {
16097  Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16098  Conv->setInvalidDecl();
16099  return;
16100  }
16101 
16102  // Create the return statement that returns the block from the conversion
16103  // function.
16104  StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
16105  if (Return.isInvalid()) {
16106  Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16107  Conv->setInvalidDecl();
16108  return;
16109  }
16110 
16111  // Set the body of the conversion function.
16112  Stmt *ReturnS = Return.get();
16114  Conv->getLocation(), Conv->getLocation()));
16115  Conv->markUsed(Context);
16116 
16117  // We're done; notify the mutation listener, if any.
16119  L->CompletedImplicitDefinition(Conv);
16120  }
16121 }
16122 
16123 /// Determine whether the given list arguments contains exactly one
16124 /// "real" (non-default) argument.
16126  switch (Args.size()) {
16127  case 0:
16128  return false;
16129 
16130  default:
16131  if (!Args[1]->isDefaultArgument())
16132  return false;
16133 
16134  [[fallthrough]];
16135  case 1:
16136  return !Args[0]->isDefaultArgument();
16137  }
16138 
16139  return false;
16140 }
16141 
16143  SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16144  CXXConstructorDecl *Constructor, MultiExprArg ExprArgs,
16145  bool HadMultipleCandidates, bool IsListInitialization,
16146  bool IsStdInitListInitialization, bool RequiresZeroInit,
16147  CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16148  bool Elidable = false;
16149 
16150  // C++0x [class.copy]p34:
16151  // When certain criteria are met, an implementation is allowed to
16152  // omit the copy/move construction of a class object, even if the
16153  // copy/move constructor and/or destructor for the object have
16154  // side effects. [...]
16155  // - when a temporary class object that has not been bound to a
16156  // reference (12.2) would be copied/moved to a class object
16157  // with the same cv-unqualified type, the copy/move operation
16158  // can be omitted by constructing the temporary object
16159  // directly into the target of the omitted copy/move
16160  if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
16161  // FIXME: Converting constructors should also be accepted.
16162  // But to fix this, the logic that digs down into a CXXConstructExpr
16163  // to find the source object needs to handle it.
16164  // Right now it assumes the source object is passed directly as the
16165  // first argument.
16166  Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
16167  Expr *SubExpr = ExprArgs[0];
16168  // FIXME: Per above, this is also incorrect if we want to accept
16169  // converting constructors, as isTemporaryObject will
16170  // reject temporaries with different type from the
16171  // CXXRecord itself.
16172  Elidable = SubExpr->isTemporaryObject(
16173  Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
16174  }
16175 
16176  return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
16177  FoundDecl, Constructor,
16178  Elidable, ExprArgs, HadMultipleCandidates,
16179  IsListInitialization,
16180  IsStdInitListInitialization, RequiresZeroInit,
16181  ConstructKind, ParenRange);
16182 }
16183 
16185  SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16186  CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16187  bool HadMultipleCandidates, bool IsListInitialization,
16188  bool IsStdInitListInitialization, bool RequiresZeroInit,
16189  CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16190  if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
16191  Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
16192  // The only way to get here is if we did overlaod resolution to find the
16193  // shadow decl, so we don't need to worry about re-checking the trailing
16194  // requires clause.
16195  if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
16196  return ExprError();
16197  }
16198 
16199  return BuildCXXConstructExpr(
16200  ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
16201  HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
16202  RequiresZeroInit, ConstructKind, ParenRange);
16203 }
16204 
16205 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
16206 /// including handling of its default argument expressions.
16208  SourceLocation ConstructLoc, QualType DeclInitType,
16209  CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16210  bool HadMultipleCandidates, bool IsListInitialization,
16211  bool IsStdInitListInitialization, bool RequiresZeroInit,
16212  CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16213  assert(declaresSameEntity(
16214  Constructor->getParent(),
16215  DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16216  "given constructor for wrong type");
16217  MarkFunctionReferenced(ConstructLoc, Constructor);
16218  if (getLangOpts().CUDA && !CUDA().CheckCall(ConstructLoc, Constructor))
16219  return ExprError();
16220 
16223  Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
16224  HadMultipleCandidates, IsListInitialization,
16225  IsStdInitListInitialization, RequiresZeroInit,
16226  static_cast<CXXConstructionKind>(ConstructKind), ParenRange),
16227  Constructor);
16228 }
16229 
16231  if (VD->isInvalidDecl()) return;
16232  // If initializing the variable failed, don't also diagnose problems with
16233  // the destructor, they're likely related.
16234  if (VD->getInit() && VD->getInit()->containsErrors())
16235  return;
16236 
16237  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
16238  if (ClassDecl->isInvalidDecl()) return;
16239  if (ClassDecl->hasIrrelevantDestructor()) return;
16240  if (ClassDecl->isDependentContext()) return;
16241 
16242  if (VD->isNoDestroy(getASTContext()))
16243  return;
16244 
16245  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
16246  // The result of `LookupDestructor` might be nullptr if the destructor is
16247  // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16248  // will not be selected by `CXXRecordDecl::getDestructor()`.
16249  if (!Destructor)
16250  return;
16251  // If this is an array, we'll require the destructor during initialization, so
16252  // we can skip over this. We still want to emit exit-time destructor warnings
16253  // though.
16254  if (!VD->getType()->isArrayType()) {
16255  MarkFunctionReferenced(VD->getLocation(), Destructor);
16256  CheckDestructorAccess(VD->getLocation(), Destructor,
16257  PDiag(diag::err_access_dtor_var)
16258  << VD->getDeclName() << VD->getType());
16259  DiagnoseUseOfDecl(Destructor, VD->getLocation());
16260  }
16261 
16262  if (Destructor->isTrivial()) return;
16263 
16264  // If the destructor is constexpr, check whether the variable has constant
16265  // destruction now.
16266  if (Destructor->isConstexpr()) {
16267  bool HasConstantInit = false;
16268  if (VD->getInit() && !VD->getInit()->isValueDependent())
16269  HasConstantInit = VD->evaluateValue();
16271  if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16272  HasConstantInit) {
16273  Diag(VD->getLocation(),
16274  diag::err_constexpr_var_requires_const_destruction) << VD;
16275  for (unsigned I = 0, N = Notes.size(); I != N; ++I)
16276  Diag(Notes[I].first, Notes[I].second);
16277  }
16278  }
16279 
16280  if (!VD->hasGlobalStorage() || !VD->needsDestruction(Context))
16281  return;
16282 
16283  // Emit warning for non-trivial dtor in global scope (a real global,
16284  // class-static, function-static).
16285  if (!VD->hasAttr<AlwaysDestroyAttr>())
16286  Diag(VD->getLocation(), diag::warn_exit_time_destructor);
16287 
16288  // TODO: this should be re-enabled for static locals by !CXAAtExit
16289  if (!VD->isStaticLocal())
16290  Diag(VD->getLocation(), diag::warn_global_destructor);
16291 }
16292 
16293 /// Given a constructor and the set of arguments provided for the
16294 /// constructor, convert the arguments and add any required default arguments
16295 /// to form a proper call to this constructor.
16296 ///
16297 /// \returns true if an error occurred, false otherwise.
16299  QualType DeclInitType, MultiExprArg ArgsPtr,
16300  SourceLocation Loc,
16301  SmallVectorImpl<Expr *> &ConvertedArgs,
16302  bool AllowExplicit,
16303  bool IsListInitialization) {
16304  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16305  unsigned NumArgs = ArgsPtr.size();
16306  Expr **Args = ArgsPtr.data();
16307 
16308  const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16309  unsigned NumParams = Proto->getNumParams();
16310 
16311  // If too few arguments are available, we'll fill in the rest with defaults.
16312  if (NumArgs < NumParams)
16313  ConvertedArgs.reserve(NumParams);
16314  else
16315  ConvertedArgs.reserve(NumArgs);
16316 
16317  VariadicCallType CallType =
16318  Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
16319  SmallVector<Expr *, 8> AllArgs;
16320  bool Invalid = GatherArgumentsForCall(
16321  Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,
16322  CallType, AllowExplicit, IsListInitialization);
16323  ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
16324 
16325  DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
16326 
16327  CheckConstructorCall(Constructor, DeclInitType,
16328  llvm::ArrayRef(AllArgs.data(), AllArgs.size()), Proto,
16329  Loc);
16330 
16331  return Invalid;
16332 }
16333 
16334 static inline bool
16336  const FunctionDecl *FnDecl) {
16337  const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16338  if (isa<NamespaceDecl>(DC)) {
16339  return SemaRef.Diag(FnDecl->getLocation(),
16340  diag::err_operator_new_delete_declared_in_namespace)
16341  << FnDecl->getDeclName();
16342  }
16343 
16344  if (isa<TranslationUnitDecl>(DC) &&
16345  FnDecl->getStorageClass() == SC_Static) {
16346  return SemaRef.Diag(FnDecl->getLocation(),
16347  diag::err_operator_new_delete_declared_static)
16348  << FnDecl->getDeclName();
16349  }
16350 
16351  return false;
16352 }
16353 
16355  const PointerType *PtrTy) {
16356  auto &Ctx = SemaRef.Context;
16357  Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16358  PtrQuals.removeAddressSpace();
16359  return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
16360  PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
16361 }
16362 
16363 static inline bool
16365  CanQualType ExpectedResultType,
16366  CanQualType ExpectedFirstParamType,
16367  unsigned DependentParamTypeDiag,
16368  unsigned InvalidParamTypeDiag) {
16369  QualType ResultType =
16370  FnDecl->getType()->castAs<FunctionType>()->getReturnType();
16371 
16372  if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16373  // The operator is valid on any address space for OpenCL.
16374  // Drop address space from actual and expected result types.
16375  if (const auto *PtrTy = ResultType->getAs<PointerType>())
16376  ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16377 
16378  if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
16379  ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
16380  }
16381 
16382  // Check that the result type is what we expect.
16383  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
16384  // Reject even if the type is dependent; an operator delete function is
16385  // required to have a non-dependent result type.
16386  return SemaRef.Diag(
16387  FnDecl->getLocation(),
16388  ResultType->isDependentType()
16389  ? diag::err_operator_new_delete_dependent_result_type
16390  : diag::err_operator_new_delete_invalid_result_type)
16391  << FnDecl->getDeclName() << ExpectedResultType;
16392  }
16393 
16394  // A function template must have at least 2 parameters.
16395  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
16396  return SemaRef.Diag(FnDecl->getLocation(),
16397  diag::err_operator_new_delete_template_too_few_parameters)
16398  << FnDecl->getDeclName();
16399 
16400  // The function decl must have at least 1 parameter.
16401  if (FnDecl->getNumParams() == 0)
16402  return SemaRef.Diag(FnDecl->getLocation(),
16403  diag::err_operator_new_delete_too_few_parameters)
16404  << FnDecl->getDeclName();
16405 
16406  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
16407  if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16408  // The operator is valid on any address space for OpenCL.
16409  // Drop address space from actual and expected first parameter types.
16410  if (const auto *PtrTy =
16411  FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
16412  FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16413 
16414  if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
16415  ExpectedFirstParamType =
16416  RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
16417  }
16418 
16419  // Check that the first parameter type is what we expect.
16420  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
16421  ExpectedFirstParamType) {
16422  // The first parameter type is not allowed to be dependent. As a tentative
16423  // DR resolution, we allow a dependent parameter type if it is the right
16424  // type anyway, to allow destroying operator delete in class templates.
16425  return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
16426  ? DependentParamTypeDiag
16427  : InvalidParamTypeDiag)
16428  << FnDecl->getDeclName() << ExpectedFirstParamType;
16429  }
16430 
16431  return false;
16432 }
16433 
16434 static bool
16436  // C++ [basic.stc.dynamic.allocation]p1:
16437  // A program is ill-formed if an allocation function is declared in a
16438  // namespace scope other than global scope or declared static in global
16439  // scope.
16441  return true;
16442 
16443  CanQualType SizeTy =
16445 
16446  // C++ [basic.stc.dynamic.allocation]p1:
16447  // The return type shall be void*. The first parameter shall have type
16448  // std::size_t.
16450  SizeTy,
16451  diag::err_operator_new_dependent_param_type,
16452  diag::err_operator_new_param_type))
16453  return true;
16454 
16455  // C++ [basic.stc.dynamic.allocation]p1:
16456  // The first parameter shall not have an associated default argument.
16457  if (FnDecl->getParamDecl(0)->hasDefaultArg())
16458  return SemaRef.Diag(FnDecl->getLocation(),
16459  diag::err_operator_new_default_arg)
16460  << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
16461 
16462  return false;
16463 }
16464 
16465 static bool
16467  // C++ [basic.stc.dynamic.deallocation]p1:
16468  // A program is ill-formed if deallocation functions are declared in a
16469  // namespace scope other than global scope or declared static in global
16470  // scope.
16472  return true;
16473 
16474  auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
16475 
16476  // C++ P0722:
16477  // Within a class C, the first parameter of a destroying operator delete
16478  // shall be of type C *. The first parameter of any other deallocation
16479  // function shall be of type void *.
16480  CanQualType ExpectedFirstParamType =
16481  MD && MD->isDestroyingOperatorDelete()
16485 
16486  // C++ [basic.stc.dynamic.deallocation]p2:
16487  // Each deallocation function shall return void
16489  SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
16490  diag::err_operator_delete_dependent_param_type,
16491  diag::err_operator_delete_param_type))
16492  return true;
16493 
16494  // C++ P0722:
16495  // A destroying operator delete shall be a usual deallocation function.
16496  if (MD && !MD->getParent()->isDependentContext() &&
16499  SemaRef.Diag(MD->getLocation(),
16500  diag::err_destroying_operator_delete_not_usual);
16501  return true;
16502  }
16503 
16504  return false;
16505 }
16506 
16507 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
16508 /// of this overloaded operator is well-formed. If so, returns false;
16509 /// otherwise, emits appropriate diagnostics and returns true.
16511  assert(FnDecl && FnDecl->isOverloadedOperator() &&
16512  "Expected an overloaded operator declaration");
16513 
16515 
16516  // C++ [over.oper]p5:
16517  // The allocation and deallocation functions, operator new,
16518  // operator new[], operator delete and operator delete[], are
16519  // described completely in 3.7.3. The attributes and restrictions
16520  // found in the rest of this subclause do not apply to them unless
16521  // explicitly stated in 3.7.3.
16522  if (Op == OO_Delete || Op == OO_Array_Delete)
16523  return CheckOperatorDeleteDeclaration(*this, FnDecl);
16524 
16525  if (Op == OO_New || Op == OO_Array_New)
16526  return CheckOperatorNewDeclaration(*this, FnDecl);
16527 
16528  // C++ [over.oper]p7:
16529  // An operator function shall either be a member function or
16530  // be a non-member function and have at least one parameter
16531  // whose type is a class, a reference to a class, an enumeration,
16532  // or a reference to an enumeration.
16533  // Note: Before C++23, a member function could not be static. The only member
16534  // function allowed to be static is the call operator function.
16535  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
16536  if (MethodDecl->isStatic()) {
16537  if (Op == OO_Call || Op == OO_Subscript)
16538  Diag(FnDecl->getLocation(),
16539  (LangOpts.CPlusPlus23
16540  ? diag::warn_cxx20_compat_operator_overload_static
16541  : diag::ext_operator_overload_static))
16542  << FnDecl;
16543  else
16544  return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
16545  << FnDecl;
16546  }
16547  } else {
16548  bool ClassOrEnumParam = false;
16549  for (auto *Param : FnDecl->parameters()) {
16550  QualType ParamType = Param->getType().getNonReferenceType();
16551  if (ParamType->isDependentType() || ParamType->isRecordType() ||
16552  ParamType->isEnumeralType()) {
16553  ClassOrEnumParam = true;
16554  break;
16555  }
16556  }
16557 
16558  if (!ClassOrEnumParam)
16559  return Diag(FnDecl->getLocation(),
16560  diag::err_operator_overload_needs_class_or_enum)
16561  << FnDecl->getDeclName();
16562  }
16563 
16564  // C++ [over.oper]p8:
16565  // An operator function cannot have default arguments (8.3.6),
16566  // except where explicitly stated below.
16567  //
16568  // Only the function-call operator (C++ [over.call]p1) and the subscript
16569  // operator (CWG2507) allow default arguments.
16570  if (Op != OO_Call) {
16571  ParmVarDecl *FirstDefaultedParam = nullptr;
16572  for (auto *Param : FnDecl->parameters()) {
16573  if (Param->hasDefaultArg()) {
16574  FirstDefaultedParam = Param;
16575  break;
16576  }
16577  }
16578  if (FirstDefaultedParam) {
16579  if (Op == OO_Subscript) {
16580  Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16581  ? diag::ext_subscript_overload
16582  : diag::error_subscript_overload)
16583  << FnDecl->getDeclName() << 1
16584  << FirstDefaultedParam->getDefaultArgRange();
16585  } else {
16586  return Diag(FirstDefaultedParam->getLocation(),
16587  diag::err_operator_overload_default_arg)
16588  << FnDecl->getDeclName()
16589  << FirstDefaultedParam->getDefaultArgRange();
16590  }
16591  }
16592  }
16593 
16594  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
16595  { false, false, false }
16596 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
16597  , { Unary, Binary, MemberOnly }
16598 #include "clang/Basic/OperatorKinds.def"
16599  };
16600 
16601  bool CanBeUnaryOperator = OperatorUses[Op][0];
16602  bool CanBeBinaryOperator = OperatorUses[Op][1];
16603  bool MustBeMemberOperator = OperatorUses[Op][2];
16604 
16605  // C++ [over.oper]p8:
16606  // [...] Operator functions cannot have more or fewer parameters
16607  // than the number required for the corresponding operator, as
16608  // described in the rest of this subclause.
16609  unsigned NumParams = FnDecl->getNumParams() +
16610  (isa<CXXMethodDecl>(FnDecl) &&
16612  ? 1
16613  : 0);
16614  if (Op != OO_Call && Op != OO_Subscript &&
16615  ((NumParams == 1 && !CanBeUnaryOperator) ||
16616  (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
16617  (NumParams > 2))) {
16618  // We have the wrong number of parameters.
16619  unsigned ErrorKind;
16620  if (CanBeUnaryOperator && CanBeBinaryOperator) {
16621  ErrorKind = 2; // 2 -> unary or binary.
16622  } else if (CanBeUnaryOperator) {
16623  ErrorKind = 0; // 0 -> unary
16624  } else {
16625  assert(CanBeBinaryOperator &&
16626  "All non-call overloaded operators are unary or binary!");
16627  ErrorKind = 1; // 1 -> binary
16628  }
16629  return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
16630  << FnDecl->getDeclName() << NumParams << ErrorKind;
16631  }
16632 
16633  if (Op == OO_Subscript && NumParams != 2) {
16634  Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16635  ? diag::ext_subscript_overload
16636  : diag::error_subscript_overload)
16637  << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
16638  }
16639 
16640  // Overloaded operators other than operator() and operator[] cannot be
16641  // variadic.
16642  if (Op != OO_Call &&
16643  FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
16644  return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
16645  << FnDecl->getDeclName();
16646  }
16647 
16648  // Some operators must be member functions.
16649  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
16650  return Diag(FnDecl->getLocation(),
16651  diag::err_operator_overload_must_be_member)
16652  << FnDecl->getDeclName();
16653  }
16654 
16655  // C++ [over.inc]p1:
16656  // The user-defined function called operator++ implements the
16657  // prefix and postfix ++ operator. If this function is a member
16658  // function with no parameters, or a non-member function with one
16659  // parameter of class or enumeration type, it defines the prefix
16660  // increment operator ++ for objects of that type. If the function
16661  // is a member function with one parameter (which shall be of type
16662  // int) or a non-member function with two parameters (the second
16663  // of which shall be of type int), it defines the postfix
16664  // increment operator ++ for objects of that type.
16665  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16666  ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
16667  QualType ParamType = LastParam->getType();
16668 
16669  if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
16670  !ParamType->isDependentType())
16671  return Diag(LastParam->getLocation(),
16672  diag::err_operator_overload_post_incdec_must_be_int)
16673  << LastParam->getType() << (Op == OO_MinusMinus);
16674  }
16675 
16676  return false;
16677 }
16678 
16679 static bool
16681  FunctionTemplateDecl *TpDecl) {
16682  TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16683 
16684  // Must have one or two template parameters.
16685  if (TemplateParams->size() == 1) {
16686  NonTypeTemplateParmDecl *PmDecl =
16687  dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
16688 
16689  // The template parameter must be a char parameter pack.
16690  if (PmDecl && PmDecl->isTemplateParameterPack() &&
16692  return false;
16693 
16694  // C++20 [over.literal]p5:
16695  // A string literal operator template is a literal operator template
16696  // whose template-parameter-list comprises a single non-type
16697  // template-parameter of class type.
16698  //
16699  // As a DR resolution, we also allow placeholders for deduced class
16700  // template specializations.
16701  if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
16702  !PmDecl->isTemplateParameterPack() &&
16703  (PmDecl->getType()->isRecordType() ||
16705  return false;
16706  } else if (TemplateParams->size() == 2) {
16707  TemplateTypeParmDecl *PmType =
16708  dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
16709  NonTypeTemplateParmDecl *PmArgs =
16710  dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
16711 
16712  // The second template parameter must be a parameter pack with the
16713  // first template parameter as its type.
16714  if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
16715  PmArgs->isTemplateParameterPack()) {
16716  const TemplateTypeParmType *TArgs =
16717  PmArgs->getType()->getAs<TemplateTypeParmType>();
16718  if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
16719  TArgs->getIndex() == PmType->getIndex()) {
16721  SemaRef.Diag(TpDecl->getLocation(),
16722  diag::ext_string_literal_operator_template);
16723  return false;
16724  }
16725  }
16726  }
16727 
16729  diag::err_literal_operator_template)
16730  << TpDecl->getTemplateParameters()->getSourceRange();
16731  return true;
16732 }
16733 
16734 /// CheckLiteralOperatorDeclaration - Check whether the declaration
16735 /// of this literal operator function is well-formed. If so, returns
16736 /// false; otherwise, emits appropriate diagnostics and returns true.
16738  if (isa<CXXMethodDecl>(FnDecl)) {
16739  Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
16740  << FnDecl->getDeclName();
16741  return true;
16742  }
16743 
16744  if (FnDecl->isExternC()) {
16745  Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
16746  if (const LinkageSpecDecl *LSD =
16747  FnDecl->getDeclContext()->getExternCContext())
16748  Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
16749  return true;
16750  }
16751 
16752  // This might be the definition of a literal operator template.
16754 
16755  // This might be a specialization of a literal operator template.
16756  if (!TpDecl)
16757  TpDecl = FnDecl->getPrimaryTemplate();
16758 
16759  // template <char...> type operator "" name() and
16760  // template <class T, T...> type operator "" name() are the only valid
16761  // template signatures, and the only valid signatures with no parameters.
16762  //
16763  // C++20 also allows template <SomeClass T> type operator "" name().
16764  if (TpDecl) {
16765  if (FnDecl->param_size() != 0) {
16766  Diag(FnDecl->getLocation(),
16767  diag::err_literal_operator_template_with_params);
16768  return true;
16769  }
16770 
16771  if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
16772  return true;
16773 
16774  } else if (FnDecl->param_size() == 1) {
16775  const ParmVarDecl *Param = FnDecl->getParamDecl(0);
16776 
16777  QualType ParamType = Param->getType().getUnqualifiedType();
16778 
16779  // Only unsigned long long int, long double, any character type, and const
16780  // char * are allowed as the only parameters.
16781  if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
16782  ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
16783  Context.hasSameType(ParamType, Context.CharTy) ||
16784  Context.hasSameType(ParamType, Context.WideCharTy) ||
16785  Context.hasSameType(ParamType, Context.Char8Ty) ||
16786  Context.hasSameType(ParamType, Context.Char16Ty) ||
16787  Context.hasSameType(ParamType, Context.Char32Ty)) {
16788  } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
16789  QualType InnerType = Ptr->getPointeeType();
16790 
16791  // Pointer parameter must be a const char *.
16792  if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
16793  Context.CharTy) &&
16794  InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
16795  Diag(Param->getSourceRange().getBegin(),
16796  diag::err_literal_operator_param)
16797  << ParamType << "'const char *'" << Param->getSourceRange();
16798  return true;
16799  }
16800 
16801  } else if (ParamType->isRealFloatingType()) {
16802  Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16803  << ParamType << Context.LongDoubleTy << Param->getSourceRange();
16804  return true;
16805 
16806  } else if (ParamType->isIntegerType()) {
16807  Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16808  << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
16809  return true;
16810 
16811  } else {
16812  Diag(Param->getSourceRange().getBegin(),
16813  diag::err_literal_operator_invalid_param)
16814  << ParamType << Param->getSourceRange();
16815  return true;
16816  }
16817 
16818  } else if (FnDecl->param_size() == 2) {
16819  FunctionDecl::param_iterator Param = FnDecl->param_begin();
16820 
16821  // First, verify that the first parameter is correct.
16822 
16823  QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
16824 
16825  // Two parameter function must have a pointer to const as a
16826  // first parameter; let's strip those qualifiers.
16827  const PointerType *PT = FirstParamType->getAs<PointerType>();
16828 
16829  if (!PT) {
16830  Diag((*Param)->getSourceRange().getBegin(),
16831  diag::err_literal_operator_param)
16832  << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16833  return true;
16834  }
16835 
16836  QualType PointeeType = PT->getPointeeType();
16837  // First parameter must be const
16838  if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
16839  Diag((*Param)->getSourceRange().getBegin(),
16840  diag::err_literal_operator_param)
16841  << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16842  return true;
16843  }
16844 
16845  QualType InnerType = PointeeType.getUnqualifiedType();
16846  // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16847  // const char32_t* are allowed as the first parameter to a two-parameter
16848  // function
16849  if (!(Context.hasSameType(InnerType, Context.CharTy) ||
16850  Context.hasSameType(InnerType, Context.WideCharTy) ||
16851  Context.hasSameType(InnerType, Context.Char8Ty) ||
16852  Context.hasSameType(InnerType, Context.Char16Ty) ||
16853  Context.hasSameType(InnerType, Context.Char32Ty))) {
16854  Diag((*Param)->getSourceRange().getBegin(),
16855  diag::err_literal_operator_param)
16856  << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16857  return true;
16858  }
16859 
16860  // Move on to the second and final parameter.
16861  ++Param;
16862 
16863  // The second parameter must be a std::size_t.
16864  QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16865  if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
16866  Diag((*Param)->getSourceRange().getBegin(),
16867  diag::err_literal_operator_param)
16868  << SecondParamType << Context.getSizeType()
16869  << (*Param)->getSourceRange();
16870  return true;
16871  }
16872  } else {
16873  Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16874  return true;
16875  }
16876 
16877  // Parameters are good.
16878 
16879  // A parameter-declaration-clause containing a default argument is not
16880  // equivalent to any of the permitted forms.
16881  for (auto *Param : FnDecl->parameters()) {
16882  if (Param->hasDefaultArg()) {
16883  Diag(Param->getDefaultArgRange().getBegin(),
16884  diag::err_literal_operator_default_argument)
16885  << Param->getDefaultArgRange();
16886  break;
16887  }
16888  }
16889 
16890  const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
16893  !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
16894  // C++23 [usrlit.suffix]p1:
16895  // Literal suffix identifiers that do not start with an underscore are
16896  // reserved for future standardization. Literal suffix identifiers that
16897  // contain a double underscore __ are reserved for use by C++
16898  // implementations.
16899  Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16900  << static_cast<int>(Status)
16902  }
16903 
16904  return false;
16905 }
16906 
16907 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
16908 /// linkage specification, including the language and (if present)
16909 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
16910 /// language string literal. LBraceLoc, if valid, provides the location of
16911 /// the '{' brace. Otherwise, this linkage specification does not
16912 /// have any braces.
16914  Expr *LangStr,
16915  SourceLocation LBraceLoc) {
16916  StringLiteral *Lit = cast<StringLiteral>(LangStr);
16917  assert(Lit->isUnevaluated() && "Unexpected string literal kind");
16918 
16919  StringRef Lang = Lit->getString();
16921  if (Lang == "C")
16923  else if (Lang == "C++")
16925  else {
16926  Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16927  << LangStr->getSourceRange();
16928  return nullptr;
16929  }
16930 
16931  // FIXME: Add all the various semantics of linkage specifications
16932 
16934  LangStr->getExprLoc(), Language,
16935  LBraceLoc.isValid());
16936 
16937  /// C++ [module.unit]p7.2.3
16938  /// - Otherwise, if the declaration
16939  /// - ...
16940  /// - ...
16941  /// - appears within a linkage-specification,
16942  /// it is attached to the global module.
16943  ///
16944  /// If the declaration is already in global module fragment, we don't
16945  /// need to attach it again.
16946  if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
16947  Module *GlobalModule = PushImplicitGlobalModuleFragment(ExternLoc);
16948  D->setLocalOwningModule(GlobalModule);
16949  }
16950 
16951  CurContext->addDecl(D);
16952  PushDeclContext(S, D);
16953  return D;
16954 }
16955 
16956 /// ActOnFinishLinkageSpecification - Complete the definition of
16957 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
16958 /// valid, it's the position of the closing '}' brace in a linkage
16959 /// specification that uses braces.
16961  Decl *LinkageSpec,
16962  SourceLocation RBraceLoc) {
16963  if (RBraceLoc.isValid()) {
16964  LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
16965  LSDecl->setRBraceLoc(RBraceLoc);
16966  }
16967 
16968  // If the current module doesn't has Parent, it implies that the
16969  // LinkageSpec isn't in the module created by itself. So we don't
16970  // need to pop it.
16971  if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
16972  getCurrentModule()->isImplicitGlobalModule() &&
16974  PopImplicitGlobalModuleFragment();
16975 
16976  PopDeclContext();
16977  return LinkageSpec;
16978 }
16979 
16981  const ParsedAttributesView &AttrList,
16982  SourceLocation SemiLoc) {
16983  Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
16984  // Attribute declarations appertain to empty declaration so we handle
16985  // them here.
16986  ProcessDeclAttributeList(S, ED, AttrList);
16987 
16988  CurContext->addDecl(ED);
16989  return ED;
16990 }
16991 
16992 /// Perform semantic analysis for the variable declaration that
16993 /// occurs within a C++ catch clause, returning the newly-created
16994 /// variable.
16996  SourceLocation StartLoc,
16997  SourceLocation Loc,
16998  const IdentifierInfo *Name) {
16999  bool Invalid = false;
17000  QualType ExDeclType = TInfo->getType();
17001 
17002  // Arrays and functions decay.
17003  if (ExDeclType->isArrayType())
17004  ExDeclType = Context.getArrayDecayedType(ExDeclType);
17005  else if (ExDeclType->isFunctionType())
17006  ExDeclType = Context.getPointerType(ExDeclType);
17007 
17008  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
17009  // The exception-declaration shall not denote a pointer or reference to an
17010  // incomplete type, other than [cv] void*.
17011  // N2844 forbids rvalue references.
17012  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
17013  Diag(Loc, diag::err_catch_rvalue_ref);
17014  Invalid = true;
17015  }
17016 
17017  if (ExDeclType->isVariablyModifiedType()) {
17018  Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
17019  Invalid = true;
17020  }
17021 
17022  QualType BaseType = ExDeclType;
17023  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
17024  unsigned DK = diag::err_catch_incomplete;
17025  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
17026  BaseType = Ptr->getPointeeType();
17027  Mode = 1;
17028  DK = diag::err_catch_incomplete_ptr;
17029  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
17030  // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
17031  BaseType = Ref->getPointeeType();
17032  Mode = 2;
17033  DK = diag::err_catch_incomplete_ref;
17034  }
17035  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
17036  !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
17037  Invalid = true;
17038 
17039  if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
17040  Diag(Loc, diag::err_wasm_reftype_tc) << 1;
17041  Invalid = true;
17042  }
17043 
17044  if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
17045  Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
17046  Invalid = true;
17047  }
17048 
17049  if (!Invalid && !ExDeclType->isDependentType() &&
17050  RequireNonAbstractType(Loc, ExDeclType,
17051  diag::err_abstract_type_in_decl,
17053  Invalid = true;
17054 
17055  // Only the non-fragile NeXT runtime currently supports C++ catches
17056  // of ObjC types, and no runtime supports catching ObjC types by value.
17057  if (!Invalid && getLangOpts().ObjC) {
17058  QualType T = ExDeclType;
17059  if (const ReferenceType *RT = T->getAs<ReferenceType>())
17060  T = RT->getPointeeType();
17061 
17062  if (T->isObjCObjectType()) {
17063  Diag(Loc, diag::err_objc_object_catch);
17064  Invalid = true;
17065  } else if (T->isObjCObjectPointerType()) {
17066  // FIXME: should this be a test for macosx-fragile specifically?
17068  Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
17069  }
17070  }
17071 
17072  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
17073  ExDeclType, TInfo, SC_None);
17074  ExDecl->setExceptionVariable(true);
17075 
17076  // In ARC, infer 'retaining' for variables of retainable type.
17077  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
17078  Invalid = true;
17079 
17080  if (!Invalid && !ExDeclType->isDependentType()) {
17081  if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
17082  // Insulate this from anything else we might currently be parsing.
17085 
17086  // C++ [except.handle]p16:
17087  // The object declared in an exception-declaration or, if the
17088  // exception-declaration does not specify a name, a temporary (12.2) is
17089  // copy-initialized (8.5) from the exception object. [...]
17090  // The object is destroyed when the handler exits, after the destruction
17091  // of any automatic objects initialized within the handler.
17092  //
17093  // We just pretend to initialize the object with itself, then make sure
17094  // it can be destroyed later.
17095  QualType initType = Context.getExceptionObjectType(ExDeclType);
17096 
17097  InitializedEntity entity =
17099  InitializationKind initKind =
17101 
17102  Expr *opaqueValue =
17103  new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
17104  InitializationSequence sequence(*this, entity, initKind, opaqueValue);
17105  ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
17106  if (result.isInvalid())
17107  Invalid = true;
17108  else {
17109  // If the constructor used was non-trivial, set this as the
17110  // "initializer".
17111  CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
17112  if (!construct->getConstructor()->isTrivial()) {
17113  Expr *init = MaybeCreateExprWithCleanups(construct);
17114  ExDecl->setInit(init);
17115  }
17116 
17117  // And make sure it's destructable.
17119  }
17120  }
17121  }
17122 
17123  if (Invalid)
17124  ExDecl->setInvalidDecl();
17125 
17126  return ExDecl;
17127 }
17128 
17129 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
17130 /// handler.
17133  bool Invalid = D.isInvalidType();
17134 
17135  // Check for unexpanded parameter packs.
17137  UPPC_ExceptionType)) {
17139  D.getIdentifierLoc());
17140  Invalid = true;
17141  }
17142 
17143  const IdentifierInfo *II = D.getIdentifier();
17144  if (NamedDecl *PrevDecl =
17147  // The scope should be freshly made just for us. There is just no way
17148  // it contains any previous declaration, except for function parameters in
17149  // a function-try-block's catch statement.
17150  assert(!S->isDeclScope(PrevDecl));
17151  if (isDeclInScope(PrevDecl, CurContext, S)) {
17152  Diag(D.getIdentifierLoc(), diag::err_redefinition)
17153  << D.getIdentifier();
17154  Diag(PrevDecl->getLocation(), diag::note_previous_definition);
17155  Invalid = true;
17156  } else if (PrevDecl->isTemplateParameter())
17157  // Maybe we will complain about the shadowed template parameter.
17159  }
17160 
17161  if (D.getCXXScopeSpec().isSet() && !Invalid) {
17162  Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
17163  << D.getCXXScopeSpec().getRange();
17164  Invalid = true;
17165  }
17166 
17168  S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
17169  if (Invalid)
17170  ExDecl->setInvalidDecl();
17171 
17172  // Add the exception declaration into this scope.
17173  if (II)
17174  PushOnScopeChains(ExDecl, S);
17175  else
17176  CurContext->addDecl(ExDecl);
17177 
17178  ProcessDeclAttributes(S, ExDecl, D);
17179  return ExDecl;
17180 }
17181 
17183  Expr *AssertExpr,
17184  Expr *AssertMessageExpr,
17185  SourceLocation RParenLoc) {
17187  return nullptr;
17188 
17189  return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
17190  AssertMessageExpr, RParenLoc, false);
17191 }
17192 
17193 static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
17194  switch (BTK) {
17195  case BuiltinType::Char_S:
17196  case BuiltinType::Char_U:
17197  break;
17198  case BuiltinType::Char8:
17199  OS << "u8";
17200  break;
17201  case BuiltinType::Char16:
17202  OS << 'u';
17203  break;
17204  case BuiltinType::Char32:
17205  OS << 'U';
17206  break;
17207  case BuiltinType::WChar_S:
17208  case BuiltinType::WChar_U:
17209  OS << 'L';
17210  break;
17211  default:
17212  llvm_unreachable("Non-character type");
17213  }
17214 }
17215 
17216 /// Convert character's value, interpreted as a code unit, to a string.
17217 /// The value needs to be zero-extended to 32-bits.
17218 /// FIXME: This assumes Unicode literal encodings
17219 static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy,
17220  unsigned TyWidth,
17221  SmallVectorImpl<char> &Str) {
17222  char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
17223  char *Ptr = Arr;
17224  BuiltinType::Kind K = BTy->getKind();
17225  llvm::raw_svector_ostream OS(Str);
17226 
17227  // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17228  // other types.
17229  if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
17230  K == BuiltinType::Char8 || Value <= 0x7F) {
17231  StringRef Escaped = escapeCStyle<EscapeChar::Single>(Value);
17232  if (!Escaped.empty())
17233  EscapeStringForDiagnostic(Escaped, Str);
17234  else
17235  OS << static_cast<char>(Value);
17236  return;
17237  }
17238 
17239  switch (K) {
17240  case BuiltinType::Char16:
17241  case BuiltinType::Char32:
17242  case BuiltinType::WChar_S:
17243  case BuiltinType::WChar_U: {
17244  if (llvm::ConvertCodePointToUTF8(Value, Ptr))
17245  EscapeStringForDiagnostic(StringRef(Arr, Ptr - Arr), Str);
17246  else
17247  OS << "\\x"
17248  << llvm::format_hex_no_prefix(Value, TyWidth / 4, /*Upper=*/true);
17249  break;
17250  }
17251  default:
17252  llvm_unreachable("Non-character type is passed");
17253  }
17254 }
17255 
17256 /// Convert \V to a string we can present to the user in a diagnostic
17257 /// \T is the type of the expression that has been evaluated into \V
17259  SmallVectorImpl<char> &Str,
17260  ASTContext &Context) {
17261  if (!V.hasValue())
17262  return false;
17263 
17264  switch (V.getKind()) {
17265  case APValue::ValueKind::Int:
17266  if (T->isBooleanType()) {
17267  // Bools are reduced to ints during evaluation, but for
17268  // diagnostic purposes we want to print them as
17269  // true or false.
17270  int64_t BoolValue = V.getInt().getExtValue();
17271  assert((BoolValue == 0 || BoolValue == 1) &&
17272  "Bool type, but value is not 0 or 1");
17273  llvm::raw_svector_ostream OS(Str);
17274  OS << (BoolValue ? "true" : "false");
17275  } else {
17276  llvm::raw_svector_ostream OS(Str);
17277  // Same is true for chars.
17278  // We want to print the character representation for textual types
17279  const auto *BTy = T->getAs<BuiltinType>();
17280  if (BTy) {
17281  switch (BTy->getKind()) {
17282  case BuiltinType::Char_S:
17283  case BuiltinType::Char_U:
17284  case BuiltinType::Char8:
17285  case BuiltinType::Char16:
17286  case BuiltinType::Char32:
17287  case BuiltinType::WChar_S:
17288  case BuiltinType::WChar_U: {
17289  unsigned TyWidth = Context.getIntWidth(T);
17290  assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17291  uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17292  WriteCharTypePrefix(BTy->getKind(), OS);
17293  OS << '\'';
17294  WriteCharValueForDiagnostic(CodeUnit, BTy, TyWidth, Str);
17295  OS << "' (0x"
17296  << llvm::format_hex_no_prefix(CodeUnit, /*Width=*/2,
17297  /*Upper=*/true)
17298  << ", " << V.getInt() << ')';
17299  return true;
17300  }
17301  default:
17302  break;
17303  }
17304  }
17305  V.getInt().toString(Str);
17306  }
17307 
17308  break;
17309 
17311  V.getFloat().toString(Str);
17312  break;
17313 
17314  case APValue::ValueKind::LValue:
17315  if (V.isNullPointer()) {
17316  llvm::raw_svector_ostream OS(Str);
17317  OS << "nullptr";
17318  } else
17319  return false;
17320  break;
17321 
17322  case APValue::ValueKind::ComplexFloat: {
17323  llvm::raw_svector_ostream OS(Str);
17324  OS << '(';
17325  V.getComplexFloatReal().toString(Str);
17326  OS << " + ";
17327  V.getComplexFloatImag().toString(Str);
17328  OS << "i)";
17329  } break;
17330 
17331  case APValue::ValueKind::ComplexInt: {
17332  llvm::raw_svector_ostream OS(Str);
17333  OS << '(';
17334  V.getComplexIntReal().toString(Str);
17335  OS << " + ";
17336  V.getComplexIntImag().toString(Str);
17337  OS << "i)";
17338  } break;
17339 
17340  default:
17341  return false;
17342  }
17343 
17344  return true;
17345 }
17346 
17347 /// Some Expression types are not useful to print notes about,
17348 /// e.g. literals and values that have already been expanded
17349 /// before such as int-valued template parameters.
17350 static bool UsefulToPrintExpr(const Expr *E) {
17351  E = E->IgnoreParenImpCasts();
17352  // Literals are pretty easy for humans to understand.
17355  return false;
17356 
17357  // These have been substituted from template parameters
17358  // and appear as literals in the static assert error.
17359  if (isa<SubstNonTypeTemplateParmExpr>(E))
17360  return false;
17361 
17362  // -5 is also simple to understand.
17363  if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
17364  return UsefulToPrintExpr(UnaryOp->getSubExpr());
17365 
17366  // Only print nested arithmetic operators.
17367  if (const auto *BO = dyn_cast<BinaryOperator>(E))
17368  return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17369  BO->isBitwiseOp());
17370 
17371  return true;
17372 }
17373 
17374 /// Try to print more useful information about a failed static_assert
17375 /// with expression \E
17377  if (const auto *Op = dyn_cast<BinaryOperator>(E);
17378  Op && Op->getOpcode() != BO_LOr) {
17379  const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17380  const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17381 
17382  // Ignore comparisons of boolean expressions with a boolean literal.
17383  if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||
17384  (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))
17385  return;
17386 
17387  // Don't print obvious expressions.
17388  if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))
17389  return;
17390 
17391  struct {
17392  const clang::Expr *Cond;
17393  Expr::EvalResult Result;
17394  SmallString<12> ValueString;
17395  bool Print;
17396  } DiagSide[2] = {{LHS, Expr::EvalResult(), {}, false},
17397  {RHS, Expr::EvalResult(), {}, false}};
17398  for (unsigned I = 0; I < 2; I++) {
17399  const Expr *Side = DiagSide[I].Cond;
17400 
17401  Side->EvaluateAsRValue(DiagSide[I].Result, Context, true);
17402 
17403  DiagSide[I].Print =
17404  ConvertAPValueToString(DiagSide[I].Result.Val, Side->getType(),
17405  DiagSide[I].ValueString, Context);
17406  }
17407  if (DiagSide[0].Print && DiagSide[1].Print) {
17408  Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
17409  << DiagSide[0].ValueString << Op->getOpcodeStr()
17410  << DiagSide[1].ValueString << Op->getSourceRange();
17411  }
17412  }
17413 }
17414 
17416  std::string &Result,
17417  ASTContext &Ctx,
17418  bool ErrorOnInvalidMessage) {
17419  assert(Message);
17420  assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17421  "can't evaluate a dependant static assert message");
17422 
17423  if (const auto *SL = dyn_cast<StringLiteral>(Message)) {
17424  assert(SL->isUnevaluated() && "expected an unevaluated string");
17425  Result.assign(SL->getString().begin(), SL->getString().end());
17426  return true;
17427  }
17428 
17429  SourceLocation Loc = Message->getBeginLoc();
17430  QualType T = Message->getType().getNonReferenceType();
17431  auto *RD = T->getAsCXXRecordDecl();
17432  if (!RD) {
17433  Diag(Loc, diag::err_static_assert_invalid_message);
17434  return false;
17435  }
17436 
17437  auto FindMember = [&](StringRef Member, bool &Empty,
17438  bool Diag = false) -> std::optional<LookupResult> {
17440  LookupResult MemberLookup(*this, DN, Loc, Sema::LookupMemberName);
17441  LookupQualifiedName(MemberLookup, RD);
17442  Empty = MemberLookup.empty();
17443  OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17445  if (MemberLookup.empty())
17446  return std::nullopt;
17447  return std::move(MemberLookup);
17448  };
17449 
17450  bool SizeNotFound, DataNotFound;
17451  std::optional<LookupResult> SizeMember = FindMember("size", SizeNotFound);
17452  std::optional<LookupResult> DataMember = FindMember("data", DataNotFound);
17453  if (SizeNotFound || DataNotFound) {
17454  Diag(Loc, diag::err_static_assert_missing_member_function)
17455  << ((SizeNotFound && DataNotFound) ? 2
17456  : SizeNotFound ? 0
17457  : 1);
17458  return false;
17459  }
17460 
17461  if (!SizeMember || !DataMember) {
17462  if (!SizeMember)
17463  FindMember("size", SizeNotFound, /*Diag=*/true);
17464  if (!DataMember)
17465  FindMember("data", DataNotFound, /*Diag=*/true);
17466  return false;
17467  }
17468 
17469  auto BuildExpr = [&](LookupResult &LR) {
17471  Message, Message->getType(), Message->getBeginLoc(), false,
17472  CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr);
17473  if (Res.isInvalid())
17474  return ExprError();
17475  Res = BuildCallExpr(nullptr, Res.get(), Loc, std::nullopt, Loc, nullptr,
17476  false, true);
17477  if (Res.isInvalid())
17478  return ExprError();
17479  if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17480  return ExprError();
17482  };
17483 
17484  ExprResult SizeE = BuildExpr(*SizeMember);
17485  ExprResult DataE = BuildExpr(*DataMember);
17486 
17487  QualType SizeT = Context.getSizeType();
17488  QualType ConstCharPtr =
17490 
17491  ExprResult EvaluatedSize =
17492  SizeE.isInvalid() ? ExprError()
17494  SizeE.get(), SizeT, CCEK_StaticAssertMessageSize);
17495  if (EvaluatedSize.isInvalid()) {
17496  Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*size*/ 0;
17497  return false;
17498  }
17499 
17500  ExprResult EvaluatedData =
17501  DataE.isInvalid()
17502  ? ExprError()
17503  : BuildConvertedConstantExpression(DataE.get(), ConstCharPtr,
17505  if (EvaluatedData.isInvalid()) {
17506  Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*data*/ 1;
17507  return false;
17508  }
17509 
17510  if (!ErrorOnInvalidMessage &&
17511  Diags.isIgnored(diag::warn_static_assert_message_constexpr, Loc))
17512  return true;
17513 
17514  Expr::EvalResult Status;
17516  Status.Diag = &Notes;
17517  if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
17518  EvaluatedData.get(), Ctx, Status) ||
17519  !Notes.empty()) {
17520  Diag(Message->getBeginLoc(),
17521  ErrorOnInvalidMessage ? diag::err_static_assert_message_constexpr
17522  : diag::warn_static_assert_message_constexpr);
17523  for (const auto &Note : Notes)
17524  Diag(Note.first, Note.second);
17525  return !ErrorOnInvalidMessage;
17526  }
17527  return true;
17528 }
17529 
17531  Expr *AssertExpr, Expr *AssertMessage,
17532  SourceLocation RParenLoc,
17533  bool Failed) {
17534  assert(AssertExpr != nullptr && "Expected non-null condition");
17535  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
17536  (!AssertMessage || (!AssertMessage->isTypeDependent() &&
17537  !AssertMessage->isValueDependent())) &&
17538  !Failed) {
17539  // In a static_assert-declaration, the constant-expression shall be a
17540  // constant expression that can be contextually converted to bool.
17541  ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
17542  if (Converted.isInvalid())
17543  Failed = true;
17544 
17545  ExprResult FullAssertExpr =
17546  ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
17547  /*DiscardedValue*/ false,
17548  /*IsConstexpr*/ true);
17549  if (FullAssertExpr.isInvalid())
17550  Failed = true;
17551  else
17552  AssertExpr = FullAssertExpr.get();
17553 
17554  llvm::APSInt Cond;
17555  Expr *BaseExpr = AssertExpr;
17556  AllowFoldKind FoldKind = NoFold;
17557 
17558  if (!getLangOpts().CPlusPlus) {
17559  // In C mode, allow folding as an extension for better compatibility with
17560  // C++ in terms of expressions like static_assert("test") or
17561  // static_assert(nullptr).
17562  FoldKind = AllowFold;
17563  }
17564 
17565  if (!Failed && VerifyIntegerConstantExpression(
17566  BaseExpr, &Cond,
17567  diag::err_static_assert_expression_is_not_constant,
17568  FoldKind).isInvalid())
17569  Failed = true;
17570 
17571  // If the static_assert passes, only verify that
17572  // the message is grammatically valid without evaluating it.
17573  if (!Failed && AssertMessage && Cond.getBoolValue()) {
17574  std::string Str;
17575  EvaluateStaticAssertMessageAsString(AssertMessage, Str, Context,
17576  /*ErrorOnInvalidMessage=*/false);
17577  }
17578 
17579  // CWG2518
17580  // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
17581  // template definition, the declaration has no effect.
17582  bool InTemplateDefinition =
17583  getLangOpts().CPlusPlus && CurContext->isDependentContext();
17584 
17585  if (!Failed && !Cond && !InTemplateDefinition) {
17586  SmallString<256> MsgBuffer;
17587  llvm::raw_svector_ostream Msg(MsgBuffer);
17588  bool HasMessage = AssertMessage;
17589  if (AssertMessage) {
17590  std::string Str;
17591  HasMessage =
17593  AssertMessage, Str, Context, /*ErrorOnInvalidMessage=*/true) ||
17594  !Str.empty();
17595  Msg << Str;
17596  }
17597  Expr *InnerCond = nullptr;
17598  std::string InnerCondDescription;
17599  std::tie(InnerCond, InnerCondDescription) =
17600  findFailedBooleanCondition(Converted.get());
17601  if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
17602  // Drill down into concept specialization expressions to see why they
17603  // weren't satisfied.
17604  Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17605  << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17606  ConstraintSatisfaction Satisfaction;
17607  if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
17608  DiagnoseUnsatisfiedConstraint(Satisfaction);
17609  } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
17610  && !isa<IntegerLiteral>(InnerCond)) {
17611  Diag(InnerCond->getBeginLoc(),
17612  diag::err_static_assert_requirement_failed)
17613  << InnerCondDescription << !HasMessage << Msg.str()
17614  << InnerCond->getSourceRange();
17615  DiagnoseStaticAssertDetails(InnerCond);
17616  } else {
17617  Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17618  << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17620  }
17621  Failed = true;
17622  }
17623  } else {
17624  ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
17625  /*DiscardedValue*/false,
17626  /*IsConstexpr*/true);
17627  if (FullAssertExpr.isInvalid())
17628  Failed = true;
17629  else
17630  AssertExpr = FullAssertExpr.get();
17631  }
17632 
17633  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
17634  AssertExpr, AssertMessage, RParenLoc,
17635  Failed);
17636 
17638  return Decl;
17639 }
17640 
17641 /// Handle a friend tag declaration where the scope specifier was
17642 /// templated.
17644  Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
17645  CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17646  const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists) {
17648 
17649  bool IsMemberSpecialization = false;
17650  bool Invalid = false;
17651 
17652  if (TemplateParameterList *TemplateParams =
17654  TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
17655  IsMemberSpecialization, Invalid)) {
17656  if (TemplateParams->size() > 0) {
17657  // This is a declaration of a class template.
17658  if (Invalid)
17659  return true;
17660 
17661  return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
17662  NameLoc, Attr, TemplateParams, AS_public,
17663  /*ModulePrivateLoc=*/SourceLocation(),
17664  FriendLoc, TempParamLists.size() - 1,
17665  TempParamLists.data()).get();
17666  } else {
17667  // The "template<>" header is extraneous.
17668  Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17670  IsMemberSpecialization = true;
17671  }
17672  }
17673 
17674  if (Invalid) return true;
17675 
17676  bool isAllExplicitSpecializations = true;
17677  for (unsigned I = TempParamLists.size(); I-- > 0; ) {
17678  if (TempParamLists[I]->size()) {
17679  isAllExplicitSpecializations = false;
17680  break;
17681  }
17682  }
17683 
17684  // FIXME: don't ignore attributes.
17685 
17686  // If it's explicit specializations all the way down, just forget
17687  // about the template header and build an appropriate non-templated
17688  // friend. TODO: for source fidelity, remember the headers.
17689  if (isAllExplicitSpecializations) {
17690  if (SS.isEmpty()) {
17691  bool Owned = false;
17692  bool IsDependent = false;
17693  return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, Attr,
17694  AS_public,
17695  /*ModulePrivateLoc=*/SourceLocation(),
17696  MultiTemplateParamsArg(), Owned, IsDependent,
17697  /*ScopedEnumKWLoc=*/SourceLocation(),
17698  /*ScopedEnumUsesClassTag=*/false,
17699  /*UnderlyingType=*/TypeResult(),
17700  /*IsTypeSpecifier=*/false,
17701  /*IsTemplateParamOrArg=*/false, /*OOK=*/OOK_Outside);
17702  }
17703 
17705  ElaboratedTypeKeyword Keyword
17707  QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
17708  *Name, NameLoc);
17709  if (T.isNull())
17710  return true;
17711 
17713  if (isa<DependentNameType>(T)) {
17716  TL.setElaboratedKeywordLoc(TagLoc);
17717  TL.setQualifierLoc(QualifierLoc);
17718  TL.setNameLoc(NameLoc);
17719  } else {
17721  TL.setElaboratedKeywordLoc(TagLoc);
17722  TL.setQualifierLoc(QualifierLoc);
17723  TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
17724  }
17725 
17726  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
17727  TSI, FriendLoc, TempParamLists);
17728  Friend->setAccess(AS_public);
17729  CurContext->addDecl(Friend);
17730  return Friend;
17731  }
17732 
17733  assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
17734 
17735 
17736 
17737  // Handle the case of a templated-scope friend class. e.g.
17738  // template <class T> class A<T>::B;
17739  // FIXME: we don't support these right now.
17740  Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
17741  << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
17743  QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
17746  TL.setElaboratedKeywordLoc(TagLoc);
17748  TL.setNameLoc(NameLoc);
17749 
17750  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
17751  TSI, FriendLoc, TempParamLists);
17752  Friend->setAccess(AS_public);
17753  Friend->setUnsupportedFriend(true);
17754  CurContext->addDecl(Friend);
17755  return Friend;
17756 }
17757 
17758 /// Handle a friend type declaration. This works in tandem with
17759 /// ActOnTag.
17760 ///
17761 /// Notes on friend class templates:
17762 ///
17763 /// We generally treat friend class declarations as if they were
17764 /// declaring a class. So, for example, the elaborated type specifier
17765 /// in a friend declaration is required to obey the restrictions of a
17766 /// class-head (i.e. no typedefs in the scope chain), template
17767 /// parameters are required to match up with simple template-ids, &c.
17768 /// However, unlike when declaring a template specialization, it's
17769 /// okay to refer to a template specialization without an empty
17770 /// template parameter declaration, e.g.
17771 /// friend class A<T>::B<unsigned>;
17772 /// We permit this as a special case; if there are any template
17773 /// parameters present at all, require proper matching, i.e.
17774 /// template <> template <class T> friend class A<int>::B;
17776  MultiTemplateParamsArg TempParams) {
17777  SourceLocation Loc = DS.getBeginLoc();
17778  SourceLocation FriendLoc = DS.getFriendSpecLoc();
17779 
17780  assert(DS.isFriendSpecified());
17782 
17783  // C++ [class.friend]p3:
17784  // A friend declaration that does not declare a function shall have one of
17785  // the following forms:
17786  // friend elaborated-type-specifier ;
17787  // friend simple-type-specifier ;
17788  // friend typename-specifier ;
17789  //
17790  // If the friend keyword isn't first, or if the declarations has any type
17791  // qualifiers, then the declaration doesn't have that form.
17793  Diag(FriendLoc, diag::err_friend_not_first_in_declaration);
17794  if (DS.getTypeQualifiers()) {
17796  Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
17798  Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
17800  Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
17802  Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
17804  Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
17805  }
17806 
17807  // Try to convert the decl specifier to a type. This works for
17808  // friend templates because ActOnTag never produces a ClassTemplateDecl
17809  // for a TUK_Friend.
17810  Declarator TheDeclarator(DS, ParsedAttributesView::none(),
17812  TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator);
17813  QualType T = TSI->getType();
17814  if (TheDeclarator.isInvalidType())
17815  return nullptr;
17816 
17818  return nullptr;
17819 
17820  if (!T->isElaboratedTypeSpecifier()) {
17821  if (TempParams.size()) {
17822  // C++23 [dcl.pre]p5:
17823  // In a simple-declaration, the optional init-declarator-list can be
17824  // omitted only when declaring a class or enumeration, that is, when
17825  // the decl-specifier-seq contains either a class-specifier, an
17826  // elaborated-type-specifier with a class-key, or an enum-specifier.
17827  //
17828  // The declaration of a template-declaration or explicit-specialization
17829  // is never a member-declaration, so this must be a simple-declaration
17830  // with no init-declarator-list. Therefore, this is ill-formed.
17831  Diag(Loc, diag::err_tagless_friend_type_template) << DS.getSourceRange();
17832  return nullptr;
17833  } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
17834  SmallString<16> InsertionText(" ");
17835  InsertionText += RD->getKindName();
17836 
17838  ? diag::warn_cxx98_compat_unelaborated_friend_type
17839  : diag::ext_unelaborated_friend_type)
17840  << (unsigned)RD->getTagKind() << T
17842  InsertionText);
17843  } else {
17844  Diag(FriendLoc, getLangOpts().CPlusPlus11
17845  ? diag::warn_cxx98_compat_nonclass_type_friend
17846  : diag::ext_nonclass_type_friend)
17847  << T << DS.getSourceRange();
17848  }
17849  }
17850 
17851  // C++98 [class.friend]p1: A friend of a class is a function
17852  // or class that is not a member of the class . . .
17853  // This is fixed in DR77, which just barely didn't make the C++03
17854  // deadline. It's also a very silly restriction that seriously
17855  // affects inner classes and which nobody else seems to implement;
17856  // thus we never diagnose it, not even in -pedantic.
17857  //
17858  // But note that we could warn about it: it's always useless to
17859  // friend one of your own members (it's not, however, worthless to
17860  // friend a member of an arbitrary specialization of your template).
17861 
17862  Decl *D;
17863  if (!TempParams.empty())
17864  D = FriendTemplateDecl::Create(Context, CurContext, Loc, TempParams, TSI,
17865  FriendLoc);
17866  else
17868  TSI, FriendLoc);
17869 
17870  if (!D)
17871  return nullptr;
17872 
17873  D->setAccess(AS_public);
17874  CurContext->addDecl(D);
17875 
17876  return D;
17877 }
17878 
17880  MultiTemplateParamsArg TemplateParams) {
17881  const DeclSpec &DS = D.getDeclSpec();
17882 
17883  assert(DS.isFriendSpecified());
17885 
17886  SourceLocation Loc = D.getIdentifierLoc();
17888 
17889  // C++ [class.friend]p1
17890  // A friend of a class is a function or class....
17891  // Note that this sees through typedefs, which is intended.
17892  // It *doesn't* see through dependent types, which is correct
17893  // according to [temp.arg.type]p3:
17894  // If a declaration acquires a function type through a
17895  // type dependent on a template-parameter and this causes
17896  // a declaration that does not use the syntactic form of a
17897  // function declarator to have a function type, the program
17898  // is ill-formed.
17899  if (!TInfo->getType()->isFunctionType()) {
17900  Diag(Loc, diag::err_unexpected_friend);
17901 
17902  // It might be worthwhile to try to recover by creating an
17903  // appropriate declaration.
17904  return nullptr;
17905  }
17906 
17907  // C++ [namespace.memdef]p3
17908  // - If a friend declaration in a non-local class first declares a
17909  // class or function, the friend class or function is a member
17910  // of the innermost enclosing namespace.
17911  // - The name of the friend is not found by simple name lookup
17912  // until a matching declaration is provided in that namespace
17913  // scope (either before or after the class declaration granting
17914  // friendship).
17915  // - If a friend function is called, its name may be found by the
17916  // name lookup that considers functions from namespaces and
17917  // classes associated with the types of the function arguments.
17918  // - When looking for a prior declaration of a class or a function
17919  // declared as a friend, scopes outside the innermost enclosing
17920  // namespace scope are not considered.
17921 
17922  CXXScopeSpec &SS = D.getCXXScopeSpec();
17924  assert(NameInfo.getName());
17925 
17926  // Check for unexpanded parameter packs.
17930  return nullptr;
17931 
17932  // The context we found the declaration in, or in which we should
17933  // create the declaration.
17934  DeclContext *DC;
17935  Scope *DCScope = S;
17936  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
17938 
17939  bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
17940 
17941  // There are five cases here.
17942  // - There's no scope specifier and we're in a local class. Only look
17943  // for functions declared in the immediately-enclosing block scope.
17944  // We recover from invalid scope qualifiers as if they just weren't there.
17945  FunctionDecl *FunctionContainingLocalClass = nullptr;
17946  if ((SS.isInvalid() || !SS.isSet()) &&
17947  (FunctionContainingLocalClass =
17948  cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
17949  // C++11 [class.friend]p11:
17950  // If a friend declaration appears in a local class and the name
17951  // specified is an unqualified name, a prior declaration is
17952  // looked up without considering scopes that are outside the
17953  // innermost enclosing non-class scope. For a friend function
17954  // declaration, if there is no prior declaration, the program is
17955  // ill-formed.
17956 
17957  // Find the innermost enclosing non-class scope. This is the block
17958  // scope containing the local class definition (or for a nested class,
17959  // the outer local class).
17960  DCScope = S->getFnParent();
17961 
17962  // Look up the function name in the scope.
17964  LookupName(Previous, S, /*AllowBuiltinCreation*/false);
17965 
17966  if (!Previous.empty()) {
17967  // All possible previous declarations must have the same context:
17968  // either they were declared at block scope or they are members of
17969  // one of the enclosing local classes.
17970  DC = Previous.getRepresentativeDecl()->getDeclContext();
17971  } else {
17972  // This is ill-formed, but provide the context that we would have
17973  // declared the function in, if we were permitted to, for error recovery.
17974  DC = FunctionContainingLocalClass;
17975  }
17977 
17978  // - There's no scope specifier, in which case we just go to the
17979  // appropriate scope and look for a function or function template
17980  // there as appropriate.
17981  } else if (SS.isInvalid() || !SS.isSet()) {
17982  // C++11 [namespace.memdef]p3:
17983  // If the name in a friend declaration is neither qualified nor
17984  // a template-id and the declaration is a function or an
17985  // elaborated-type-specifier, the lookup to determine whether
17986  // the entity has been previously declared shall not consider
17987  // any scopes outside the innermost enclosing namespace.
17988 
17989  // Find the appropriate context according to the above.
17990  DC = CurContext;
17991 
17992  // Skip class contexts. If someone can cite chapter and verse
17993  // for this behavior, that would be nice --- it's what GCC and
17994  // EDG do, and it seems like a reasonable intent, but the spec
17995  // really only says that checks for unqualified existing
17996  // declarations should stop at the nearest enclosing namespace,
17997  // not that they should only consider the nearest enclosing
17998  // namespace.
17999  while (DC->isRecord())
18000  DC = DC->getParent();
18001 
18002  DeclContext *LookupDC = DC->getNonTransparentContext();
18003  while (true) {
18004  LookupQualifiedName(Previous, LookupDC);
18005 
18006  if (!Previous.empty()) {
18007  DC = LookupDC;
18008  break;
18009  }
18010 
18011  if (isTemplateId) {
18012  if (isa<TranslationUnitDecl>(LookupDC)) break;
18013  } else {
18014  if (LookupDC->isFileContext()) break;
18015  }
18016  LookupDC = LookupDC->getParent();
18017  }
18018 
18019  DCScope = getScopeForDeclContext(S, DC);
18020 
18021  // - There's a non-dependent scope specifier, in which case we
18022  // compute it and do a previous lookup there for a function
18023  // or function template.
18024  } else if (!SS.getScopeRep()->isDependent()) {
18025  DC = computeDeclContext(SS);
18026  if (!DC) return nullptr;
18027 
18028  if (RequireCompleteDeclContext(SS, DC)) return nullptr;
18029 
18031 
18032  // C++ [class.friend]p1: A friend of a class is a function or
18033  // class that is not a member of the class . . .
18034  if (DC->Equals(CurContext))
18035  Diag(DS.getFriendSpecLoc(),
18037  diag::warn_cxx98_compat_friend_is_member :
18038  diag::err_friend_is_member);
18039 
18040  // - There's a scope specifier that does not match any template
18041  // parameter lists, in which case we use some arbitrary context,
18042  // create a method or method template, and wait for instantiation.
18043  // - There's a scope specifier that does match some template
18044  // parameter lists, which we don't handle right now.
18045  } else {
18046  DC = CurContext;
18047  assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
18048  }
18049 
18050  if (!DC->isRecord()) {
18051  int DiagArg = -1;
18052  switch (D.getName().getKind()) {
18055  DiagArg = 0;
18056  break;
18058  DiagArg = 1;
18059  break;
18061  DiagArg = 2;
18062  break;
18064  DiagArg = 3;
18065  break;
18071  break;
18072  }
18073  // This implies that it has to be an operator or function.
18074  if (DiagArg >= 0) {
18075  Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
18076  return nullptr;
18077  }
18078  }
18079 
18080  // FIXME: This is an egregious hack to cope with cases where the scope stack
18081  // does not contain the declaration context, i.e., in an out-of-line
18082  // definition of a class.
18083  Scope FakeDCScope(S, Scope::DeclScope, Diags);
18084  if (!DCScope) {
18085  FakeDCScope.setEntity(DC);
18086  DCScope = &FakeDCScope;
18087  }
18088 
18089  bool AddToScope = true;
18090  NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
18091  TemplateParams, AddToScope);
18092  if (!ND) return nullptr;
18093 
18094  assert(ND->getLexicalDeclContext() == CurContext);
18095 
18096  // If we performed typo correction, we might have added a scope specifier
18097  // and changed the decl context.
18098  DC = ND->getDeclContext();
18099 
18100  // Add the function declaration to the appropriate lookup tables,
18101  // adjusting the redeclarations list as necessary. We don't
18102  // want to do this yet if the friending class is dependent.
18103  //
18104  // Also update the scope-based lookup if the target context's
18105  // lookup context is in lexical scope.
18106  if (!CurContext->isDependentContext()) {
18107  DC = DC->getRedeclContext();
18108  DC->makeDeclVisibleInContext(ND);
18109  if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18110  PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
18111  }
18112 
18114  D.getIdentifierLoc(), ND,
18115  DS.getFriendSpecLoc());
18116  FrD->setAccess(AS_public);
18117  CurContext->addDecl(FrD);
18118 
18119  if (ND->isInvalidDecl()) {
18120  FrD->setInvalidDecl();
18121  } else {
18122  if (DC->isRecord()) CheckFriendAccess(ND);
18123 
18124  FunctionDecl *FD;
18125  if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
18126  FD = FTD->getTemplatedDecl();
18127  else
18128  FD = cast<FunctionDecl>(ND);
18129 
18130  // C++ [class.friend]p6:
18131  // A function may be defined in a friend declaration of a class if and
18132  // only if the class is a non-local class, and the function name is
18133  // unqualified.
18134  if (D.isFunctionDefinition()) {
18135  // Qualified friend function definition.
18136  if (SS.isNotEmpty()) {
18137  // FIXME: We should only do this if the scope specifier names the
18138  // innermost enclosing namespace; otherwise the fixit changes the
18139  // meaning of the code.
18141  Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
18142 
18143  DB << SS.getScopeRep();
18144  if (DC->isFileContext())
18145  DB << FixItHint::CreateRemoval(SS.getRange());
18146 
18147  // Friend function defined in a local class.
18148  } else if (FunctionContainingLocalClass) {
18149  Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
18150 
18151  // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
18152  // a template-id, the function name is not unqualified because these is
18153  // no name. While the wording requires some reading in-between the
18154  // lines, GCC, MSVC, and EDG all consider a friend function
18155  // specialization definitions // to be de facto explicit specialization
18156  // and diagnose them as such.
18157  } else if (isTemplateId) {
18158  Diag(NameInfo.getBeginLoc(), diag::err_friend_specialization_def);
18159  }
18160  }
18161 
18162  // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
18163  // default argument expression, that declaration shall be a definition
18164  // and shall be the only declaration of the function or function
18165  // template in the translation unit.
18167  // We can't look at FD->getPreviousDecl() because it may not have been set
18168  // if we're in a dependent context. If the function is known to be a
18169  // redeclaration, we will have narrowed Previous down to the right decl.
18170  if (D.isRedeclaration()) {
18171  Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
18172  Diag(Previous.getRepresentativeDecl()->getLocation(),
18173  diag::note_previous_declaration);
18174  } else if (!D.isFunctionDefinition())
18175  Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
18176  }
18177 
18178  // Mark templated-scope function declarations as unsupported.
18179  if (FD->getNumTemplateParameterLists() && SS.isValid()) {
18180  Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
18181  << SS.getScopeRep() << SS.getRange()
18182  << cast<CXXRecordDecl>(CurContext);
18183  FrD->setUnsupportedFriend(true);
18184  }
18185  }
18186 
18188 
18189  return ND;
18190 }
18191 
18193  StringLiteral *Message) {
18194  AdjustDeclIfTemplate(Dcl);
18195 
18196  FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
18197  if (!Fn) {
18198  Diag(DelLoc, diag::err_deleted_non_function);
18199  return;
18200  }
18201 
18202  // Deleted function does not have a body.
18203  Fn->setWillHaveBody(false);
18204 
18205  if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
18206  // Don't consider the implicit declaration we generate for explicit
18207  // specializations. FIXME: Do not generate these implicit declarations.
18208  if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
18209  Prev->getPreviousDecl()) &&
18210  !Prev->isDefined()) {
18211  Diag(DelLoc, diag::err_deleted_decl_not_first);
18212  Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
18213  Prev->isImplicit() ? diag::note_previous_implicit_declaration
18214  : diag::note_previous_declaration);
18215  // We can't recover from this; the declaration might have already
18216  // been used.
18217  Fn->setInvalidDecl();
18218  return;
18219  }
18220 
18221  // To maintain the invariant that functions are only deleted on their first
18222  // declaration, mark the implicitly-instantiated declaration of the
18223  // explicitly-specialized function as deleted instead of marking the
18224  // instantiated redeclaration.
18225  Fn = Fn->getCanonicalDecl();
18226  }
18227 
18228  // dllimport/dllexport cannot be deleted.
18229  if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
18230  Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
18231  Fn->setInvalidDecl();
18232  }
18233 
18234  // C++11 [basic.start.main]p3:
18235  // A program that defines main as deleted [...] is ill-formed.
18236  if (Fn->isMain())
18237  Diag(DelLoc, diag::err_deleted_main);
18238 
18239  // C++11 [dcl.fct.def.delete]p4:
18240  // A deleted function is implicitly inline.
18241  Fn->setImplicitlyInline();
18242  Fn->setDeletedAsWritten(true, Message);
18243 }
18244 
18246  if (!Dcl || Dcl->isInvalidDecl())
18247  return;
18248 
18249  auto *FD = dyn_cast<FunctionDecl>(Dcl);
18250  if (!FD) {
18251  if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
18252  if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
18253  Diag(DefaultLoc, diag::err_defaulted_comparison_template);
18254  return;
18255  }
18256  }
18257 
18258  Diag(DefaultLoc, diag::err_default_special_members)
18259  << getLangOpts().CPlusPlus20;
18260  return;
18261  }
18262 
18263  // Reject if this can't possibly be a defaultable function.
18265  if (!DefKind &&
18266  // A dependent function that doesn't locally look defaultable can
18267  // still instantiate to a defaultable function if it's a constructor
18268  // or assignment operator.
18269  (!FD->isDependentContext() ||
18270  (!isa<CXXConstructorDecl>(FD) &&
18271  FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18272  Diag(DefaultLoc, diag::err_default_special_members)
18273  << getLangOpts().CPlusPlus20;
18274  return;
18275  }
18276 
18277  // Issue compatibility warning. We already warned if the operator is
18278  // 'operator<=>' when parsing the '<=>' token.
18279  if (DefKind.isComparison() &&
18281  Diag(DefaultLoc, getLangOpts().CPlusPlus20
18282  ? diag::warn_cxx17_compat_defaulted_comparison
18283  : diag::ext_defaulted_comparison);
18284  }
18285 
18286  FD->setDefaulted();
18287  FD->setExplicitlyDefaulted();
18288  FD->setDefaultLoc(DefaultLoc);
18289 
18290  // Defer checking functions that are defaulted in a dependent context.
18291  if (FD->isDependentContext())
18292  return;
18293 
18294  // Unset that we will have a body for this function. We might not,
18295  // if it turns out to be trivial, and we don't need this marking now
18296  // that we've marked it as defaulted.
18297  FD->setWillHaveBody(false);
18298 
18299  if (DefKind.isComparison()) {
18300  // If this comparison's defaulting occurs within the definition of its
18301  // lexical class context, we have to do the checking when complete.
18302  if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
18303  if (!RD->isCompleteDefinition())
18304  return;
18305  }
18306 
18307  // If this member fn was defaulted on its first declaration, we will have
18308  // already performed the checking in CheckCompletedCXXClass. Such a
18309  // declaration doesn't trigger an implicit definition.
18310  if (isa<CXXMethodDecl>(FD)) {
18311  const FunctionDecl *Primary = FD;
18312  if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
18313  // Ask the template instantiation pattern that actually had the
18314  // '= default' on it.
18315  Primary = Pattern;
18316  if (Primary->getCanonicalDecl()->isDefaulted())
18317  return;
18318  }
18319 
18320  if (DefKind.isComparison()) {
18321  if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
18322  FD->setInvalidDecl();
18323  else
18324  DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
18325  } else {
18326  auto *MD = cast<CXXMethodDecl>(FD);
18327 
18329  DefaultLoc))
18330  MD->setInvalidDecl();
18331  else
18332  DefineDefaultedFunction(*this, MD, DefaultLoc);
18333  }
18334 }
18335 
18336 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
18337  for (Stmt *SubStmt : S->children()) {
18338  if (!SubStmt)
18339  continue;
18340  if (isa<ReturnStmt>(SubStmt))
18341  Self.Diag(SubStmt->getBeginLoc(),
18342  diag::err_return_in_constructor_handler);
18343  if (!isa<Expr>(SubStmt))
18344  SearchForReturnInStmt(Self, SubStmt);
18345  }
18346 }
18347 
18349  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
18350  CXXCatchStmt *Handler = TryBlock->getHandler(I);
18351  SearchForReturnInStmt(*this, Handler);
18352  }
18353 }
18354 
18356  StringLiteral *DeletedMessage) {
18357  switch (BodyKind) {
18358  case FnBodyKind::Delete:
18359  SetDeclDeleted(D, Loc, DeletedMessage);
18360  break;
18361  case FnBodyKind::Default:
18362  SetDeclDefaulted(D, Loc);
18363  break;
18364  case FnBodyKind::Other:
18365  llvm_unreachable(
18366  "Parsed function body should be '= delete;' or '= default;'");
18367  }
18368 }
18369 
18371  const CXXMethodDecl *Old) {
18372  const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18373  const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
18374 
18375  if (OldFT->hasExtParameterInfos()) {
18376  for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
18377  // A parameter of the overriding method should be annotated with noescape
18378  // if the corresponding parameter of the overridden method is annotated.
18379  if (OldFT->getExtParameterInfo(I).isNoEscape() &&
18380  !NewFT->getExtParameterInfo(I).isNoEscape()) {
18381  Diag(New->getParamDecl(I)->getLocation(),
18382  diag::warn_overriding_method_missing_noescape);
18383  Diag(Old->getParamDecl(I)->getLocation(),
18384  diag::note_overridden_marked_noescape);
18385  }
18386  }
18387 
18388  // SME attributes must match when overriding a function declaration.
18389  if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
18390  Diag(New->getLocation(), diag::err_conflicting_overriding_attributes)
18391  << New << New->getType() << Old->getType();
18392  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18393  return true;
18394  }
18395 
18396  // Virtual overrides must have the same code_seg.
18397  const auto *OldCSA = Old->getAttr<CodeSegAttr>();
18398  const auto *NewCSA = New->getAttr<CodeSegAttr>();
18399  if ((NewCSA || OldCSA) &&
18400  (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
18401  Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
18402  Diag(Old->getLocation(), diag::note_previous_declaration);
18403  return true;
18404  }
18405 
18406  CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
18407 
18408  // If the calling conventions match, everything is fine
18409  if (NewCC == OldCC)
18410  return false;
18411 
18412  // If the calling conventions mismatch because the new function is static,
18413  // suppress the calling convention mismatch error; the error about static
18414  // function override (err_static_overrides_virtual from
18415  // Sema::CheckFunctionDeclaration) is more clear.
18416  if (New->getStorageClass() == SC_Static)
18417  return false;
18418 
18419  Diag(New->getLocation(),
18420  diag::err_conflicting_overriding_cc_attributes)
18421  << New->getDeclName() << New->getType() << Old->getType();
18422  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18423  return true;
18424 }
18425 
18427  const CXXMethodDecl *Old) {
18428  // CWG2553
18429  // A virtual function shall not be an explicit object member function.
18430  if (!New->isExplicitObjectMemberFunction())
18431  return true;
18432  Diag(New->getParamDecl(0)->getBeginLoc(),
18433  diag::err_explicit_object_parameter_nonmember)
18434  << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
18435  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18436  New->setInvalidDecl();
18437  return false;
18438 }
18439 
18441  const CXXMethodDecl *Old) {
18442  QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
18443  QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
18444 
18445  if (Context.hasSameType(NewTy, OldTy) ||
18446  NewTy->isDependentType() || OldTy->isDependentType())
18447  return false;
18448 
18449  // Check if the return types are covariant
18450  QualType NewClassTy, OldClassTy;
18451 
18452  /// Both types must be pointers or references to classes.
18453  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
18454  if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
18455  NewClassTy = NewPT->getPointeeType();
18456  OldClassTy = OldPT->getPointeeType();
18457  }
18458  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
18459  if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
18460  if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
18461  NewClassTy = NewRT->getPointeeType();
18462  OldClassTy = OldRT->getPointeeType();
18463  }
18464  }
18465  }
18466 
18467  // The return types aren't either both pointers or references to a class type.
18468  if (NewClassTy.isNull()) {
18469  Diag(New->getLocation(),
18470  diag::err_different_return_type_for_overriding_virtual_function)
18471  << New->getDeclName() << NewTy << OldTy
18472  << New->getReturnTypeSourceRange();
18473  Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18474  << Old->getReturnTypeSourceRange();
18475 
18476  return true;
18477  }
18478 
18479  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
18480  // C++14 [class.virtual]p8:
18481  // If the class type in the covariant return type of D::f differs from
18482  // that of B::f, the class type in the return type of D::f shall be
18483  // complete at the point of declaration of D::f or shall be the class
18484  // type D.
18485  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
18486  if (!RT->isBeingDefined() &&
18487  RequireCompleteType(New->getLocation(), NewClassTy,
18488  diag::err_covariant_return_incomplete,
18489  New->getDeclName()))
18490  return true;
18491  }
18492 
18493  // Check if the new class derives from the old class.
18494  if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
18495  Diag(New->getLocation(), diag::err_covariant_return_not_derived)
18496  << New->getDeclName() << NewTy << OldTy
18497  << New->getReturnTypeSourceRange();
18498  Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18499  << Old->getReturnTypeSourceRange();
18500  return true;
18501  }
18502 
18503  // Check if we the conversion from derived to base is valid.
18505  NewClassTy, OldClassTy,
18506  diag::err_covariant_return_inaccessible_base,
18507  diag::err_covariant_return_ambiguous_derived_to_base_conv,
18508  New->getLocation(), New->getReturnTypeSourceRange(),
18509  New->getDeclName(), nullptr)) {
18510  // FIXME: this note won't trigger for delayed access control
18511  // diagnostics, and it's impossible to get an undelayed error
18512  // here from access control during the original parse because
18513  // the ParsingDeclSpec/ParsingDeclarator are still in scope.
18514  Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18515  << Old->getReturnTypeSourceRange();
18516  return true;
18517  }
18518  }
18519 
18520  // The qualifiers of the return types must be the same.
18521  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
18522  Diag(New->getLocation(),
18523  diag::err_covariant_return_type_different_qualifications)
18524  << New->getDeclName() << NewTy << OldTy
18525  << New->getReturnTypeSourceRange();
18526  Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18527  << Old->getReturnTypeSourceRange();
18528  return true;
18529  }
18530 
18531 
18532  // The new class type must have the same or less qualifiers as the old type.
18533  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
18534  Diag(New->getLocation(),
18535  diag::err_covariant_return_type_class_type_more_qualified)
18536  << New->getDeclName() << NewTy << OldTy
18537  << New->getReturnTypeSourceRange();
18538  Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18539  << Old->getReturnTypeSourceRange();
18540  return true;
18541  }
18542 
18543  return false;
18544 }
18545 
18546 /// Mark the given method pure.
18547 ///
18548 /// \param Method the method to be marked pure.
18549 ///
18550 /// \param InitRange the source range that covers the "0" initializer.
18552  SourceLocation EndLoc = InitRange.getEnd();
18553  if (EndLoc.isValid())
18554  Method->setRangeEnd(EndLoc);
18555 
18556  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
18557  Method->setIsPureVirtual();
18558  return false;
18559  }
18560 
18561  if (!Method->isInvalidDecl())
18562  Diag(Method->getLocation(), diag::err_non_virtual_pure)
18563  << Method->getDeclName() << InitRange;
18564  return true;
18565 }
18566 
18568  if (D->getFriendObjectKind())
18569  Diag(D->getLocation(), diag::err_pure_friend);
18570  else if (auto *M = dyn_cast<CXXMethodDecl>(D))
18571  CheckPureMethod(M, ZeroLoc);
18572  else
18573  Diag(D->getLocation(), diag::err_illegal_initializer);
18574 }
18575 
18576 /// Determine whether the given declaration is a global variable or
18577 /// static data member.
18578 static bool isNonlocalVariable(const Decl *D) {
18579  if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
18580  return Var->hasGlobalStorage();
18581 
18582  return false;
18583 }
18584 
18585 /// Invoked when we are about to parse an initializer for the declaration
18586 /// 'Dcl'.
18587 ///
18588 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
18589 /// static data member of class X, names should be looked up in the scope of
18590 /// class X. If the declaration had a scope specifier, a scope will have
18591 /// been created and passed in for this purpose. Otherwise, S will be null.
18593  // If there is no declaration, there was an error parsing it.
18594  if (!D || D->isInvalidDecl())
18595  return;
18596 
18597  // We will always have a nested name specifier here, but this declaration
18598  // might not be out of line if the specifier names the current namespace:
18599  // extern int n;
18600  // int ::n = 0;
18601  if (S && D->isOutOfLine())
18603 
18604  // If we are parsing the initializer for a static data member, push a
18605  // new expression evaluation context that is associated with this static
18606  // data member.
18607  if (isNonlocalVariable(D))
18610 }
18611 
18612 /// Invoked after we are finished parsing an initializer for the declaration D.
18614  // If there is no declaration, there was an error parsing it.
18615  if (!D || D->isInvalidDecl())
18616  return;
18617 
18618  if (isNonlocalVariable(D))
18620 
18621  if (S && D->isOutOfLine())
18623 }
18624 
18625 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
18626 /// C++ if/switch/while/for statement.
18627 /// e.g: "if (int x = f()) {...}"
18629  // C++ 6.4p2:
18630  // The declarator shall not specify a function or an array.
18631  // The type-specifier-seq shall not contain typedef and shall not declare a
18632  // new class or enumeration.
18634  "Parser allowed 'typedef' as storage class of condition decl.");
18635 
18636  Decl *Dcl = ActOnDeclarator(S, D);
18637  if (!Dcl)
18638  return true;
18639 
18640  if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
18641  Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
18642  << D.getSourceRange();
18643  return true;
18644  }
18645 
18646  if (auto *VD = dyn_cast<VarDecl>(Dcl))
18647  VD->setCXXCondDecl();
18648 
18649  return Dcl;
18650 }
18651 
18653  if (!ExternalSource)
18654  return;
18655 
18657  ExternalSource->ReadUsedVTables(VTables);
18658  SmallVector<VTableUse, 4> NewUses;
18659  for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
18660  llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
18661  = VTablesUsed.find(VTables[I].Record);
18662  // Even if a definition wasn't required before, it may be required now.
18663  if (Pos != VTablesUsed.end()) {
18664  if (!Pos->second && VTables[I].DefinitionRequired)
18665  Pos->second = true;
18666  continue;
18667  }
18668 
18669  VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
18670  NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
18671  }
18672 
18673  VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
18674 }
18675 
18677  bool DefinitionRequired) {
18678  // Ignore any vtable uses in unevaluated operands or for classes that do
18679  // not have a vtable.
18680  if (!Class->isDynamicClass() || Class->isDependentContext() ||
18682  return;
18683  // Do not mark as used if compiling for the device outside of the target
18684  // region.
18685  if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
18686  !OpenMP().isInOpenMPDeclareTargetContext() &&
18687  !OpenMP().isInOpenMPTargetExecutionDirective()) {
18688  if (!DefinitionRequired)
18690  return;
18691  }
18692 
18693  // Try to insert this class into the map.
18695  Class = Class->getCanonicalDecl();
18696  std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
18697  Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
18698  if (!Pos.second) {
18699  // If we already had an entry, check to see if we are promoting this vtable
18700  // to require a definition. If so, we need to reappend to the VTableUses
18701  // list, since we may have already processed the first entry.
18702  if (DefinitionRequired && !Pos.first->second) {
18703  Pos.first->second = true;
18704  } else {
18705  // Otherwise, we can early exit.
18706  return;
18707  }
18708  } else {
18709  // The Microsoft ABI requires that we perform the destructor body
18710  // checks (i.e. operator delete() lookup) when the vtable is marked used, as
18711  // the deleting destructor is emitted with the vtable, not with the
18712  // destructor definition as in the Itanium ABI.
18714  CXXDestructorDecl *DD = Class->getDestructor();
18715  if (DD && DD->isVirtual() && !DD->isDeleted()) {
18716  if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
18717  // If this is an out-of-line declaration, marking it referenced will
18718  // not do anything. Manually call CheckDestructor to look up operator
18719  // delete().
18720  ContextRAII SavedContext(*this, DD);
18721  CheckDestructor(DD);
18722  } else {
18723  MarkFunctionReferenced(Loc, Class->getDestructor());
18724  }
18725  }
18726  }
18727  }
18728 
18729  // Local classes need to have their virtual members marked
18730  // immediately. For all other classes, we mark their virtual members
18731  // at the end of the translation unit.
18732  if (Class->isLocalClass())
18733  MarkVirtualMembersReferenced(Loc, Class->getDefinition());
18734  else
18735  VTableUses.push_back(std::make_pair(Class, Loc));
18736 }
18737 
18740  if (VTableUses.empty())
18741  return false;
18742 
18743  // Note: The VTableUses vector could grow as a result of marking
18744  // the members of a class as "used", so we check the size each
18745  // time through the loop and prefer indices (which are stable) to
18746  // iterators (which are not).
18747  bool DefinedAnything = false;
18748  for (unsigned I = 0; I != VTableUses.size(); ++I) {
18749  CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
18750  if (!Class)
18751  continue;
18752  TemplateSpecializationKind ClassTSK =
18753  Class->getTemplateSpecializationKind();
18754 
18755  SourceLocation Loc = VTableUses[I].second;
18756 
18757  bool DefineVTable = true;
18758 
18759  // If this class has a key function, but that key function is
18760  // defined in another translation unit, we don't need to emit the
18761  // vtable even though we're using it.
18762  const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
18763  if (KeyFunction && !KeyFunction->hasBody()) {
18764  // The key function is in another translation unit.
18765  DefineVTable = false;
18767  KeyFunction->getTemplateSpecializationKind();
18768  assert(TSK != TSK_ExplicitInstantiationDefinition &&
18769  TSK != TSK_ImplicitInstantiation &&
18770  "Instantiations don't have key functions");
18771  (void)TSK;
18772  } else if (!KeyFunction) {
18773  // If we have a class with no key function that is the subject
18774  // of an explicit instantiation declaration, suppress the
18775  // vtable; it will live with the explicit instantiation
18776  // definition.
18777  bool IsExplicitInstantiationDeclaration =
18779  for (auto *R : Class->redecls()) {
18781  = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
18783  IsExplicitInstantiationDeclaration = true;
18784  else if (TSK == TSK_ExplicitInstantiationDefinition) {
18785  IsExplicitInstantiationDeclaration = false;
18786  break;
18787  }
18788  }
18789 
18790  if (IsExplicitInstantiationDeclaration)
18791  DefineVTable = false;
18792  }
18793 
18794  // The exception specifications for all virtual members may be needed even
18795  // if we are not providing an authoritative form of the vtable in this TU.
18796  // We may choose to emit it available_externally anyway.
18797  if (!DefineVTable) {
18799  continue;
18800  }
18801 
18802  // Mark all of the virtual members of this class as referenced, so
18803  // that we can build a vtable. Then, tell the AST consumer that a
18804  // vtable for this class is required.
18805  DefinedAnything = true;
18807  CXXRecordDecl *Canonical = Class->getCanonicalDecl();
18808  if (VTablesUsed[Canonical])
18810 
18811  // Warn if we're emitting a weak vtable. The vtable will be weak if there is
18812  // no key function or the key function is inlined. Don't warn in C++ ABIs
18813  // that lack key functions, since the user won't be able to make one.
18815  Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
18817  const FunctionDecl *KeyFunctionDef = nullptr;
18818  if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
18819  KeyFunctionDef->isInlined()))
18820  Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
18821  }
18822  }
18823  VTableUses.clear();
18824 
18825  return DefinedAnything;
18826 }
18827 
18829  const CXXRecordDecl *RD) {
18830  for (const auto *I : RD->methods())
18831  if (I->isVirtual() && !I->isPureVirtual())
18832  ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
18833 }
18834 
18836  const CXXRecordDecl *RD,
18837  bool ConstexprOnly) {
18838  // Mark all functions which will appear in RD's vtable as used.
18839  CXXFinalOverriderMap FinalOverriders;
18840  RD->getFinalOverriders(FinalOverriders);
18841  for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
18842  E = FinalOverriders.end();
18843  I != E; ++I) {
18844  for (OverridingMethods::const_iterator OI = I->second.begin(),
18845  OE = I->second.end();
18846  OI != OE; ++OI) {
18847  assert(OI->second.size() > 0 && "no final overrider");
18848  CXXMethodDecl *Overrider = OI->second.front().Method;
18849 
18850  // C++ [basic.def.odr]p2:
18851  // [...] A virtual member function is used if it is not pure. [...]
18852  if (!Overrider->isPureVirtual() &&
18853  (!ConstexprOnly || Overrider->isConstexpr()))
18854  MarkFunctionReferenced(Loc, Overrider);
18855  }
18856  }
18857 
18858  // Only classes that have virtual bases need a VTT.
18859  if (RD->getNumVBases() == 0)
18860  return;
18861 
18862  for (const auto &I : RD->bases()) {
18863  const auto *Base =
18864  cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
18865  if (Base->getNumVBases() == 0)
18866  continue;
18868  }
18869 }
18870 
18871 /// SetIvarInitializers - This routine builds initialization ASTs for the
18872 /// Objective-C implementation whose ivars need be initialized.
18874  if (!getLangOpts().CPlusPlus)
18875  return;
18876  if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
18879  if (ivars.empty())
18880  return;
18882  for (unsigned i = 0; i < ivars.size(); i++) {
18883  FieldDecl *Field = ivars[i];
18884  if (Field->isInvalidDecl())
18885  continue;
18886 
18889  InitializationKind InitKind =
18890  InitializationKind::CreateDefault(ObjCImplementation->getLocation());
18891 
18892  InitializationSequence InitSeq(*this, InitEntity, InitKind, std::nullopt);
18893  ExprResult MemberInit =
18894  InitSeq.Perform(*this, InitEntity, InitKind, std::nullopt);
18895  MemberInit = MaybeCreateExprWithCleanups(MemberInit);
18896  // Note, MemberInit could actually come back empty if no initialization
18897  // is required (e.g., because it would call a trivial default constructor)
18898  if (!MemberInit.get() || MemberInit.isInvalid())
18899  continue;
18900 
18901  Member =
18903  SourceLocation(),
18904  MemberInit.getAs<Expr>(),
18905  SourceLocation());
18906  AllToInit.push_back(Member);
18907 
18908  // Be sure that the destructor is accessible and is marked as referenced.
18909  if (const RecordType *RecordTy =
18910  Context.getBaseElementType(Field->getType())
18911  ->getAs<RecordType>()) {
18912  CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
18913  if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
18914  MarkFunctionReferenced(Field->getLocation(), Destructor);
18915  CheckDestructorAccess(Field->getLocation(), Destructor,
18916  PDiag(diag::err_access_dtor_ivar)
18917  << Context.getBaseElementType(Field->getType()));
18918  }
18919  }
18920  }
18921  ObjCImplementation->setIvarInitializers(Context,
18922  AllToInit.data(), AllToInit.size());
18923  }
18924 }
18925 
18926 static
18931  Sema &S) {
18932  if (Ctor->isInvalidDecl())
18933  return;
18934 
18936 
18937  // Target may not be determinable yet, for instance if this is a dependent
18938  // call in an uninstantiated template.
18939  if (Target) {
18940  const FunctionDecl *FNTarget = nullptr;
18941  (void)Target->hasBody(FNTarget);
18942  Target = const_cast<CXXConstructorDecl*>(
18943  cast_or_null<CXXConstructorDecl>(FNTarget));
18944  }
18945 
18946  CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
18947  // Avoid dereferencing a null pointer here.
18948  *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
18949 
18950  if (!Current.insert(Canonical).second)
18951  return;
18952 
18953  // We know that beyond here, we aren't chaining into a cycle.
18954  if (!Target || !Target->isDelegatingConstructor() ||
18955  Target->isInvalidDecl() || Valid.count(TCanonical)) {
18956  Valid.insert(Current.begin(), Current.end());
18957  Current.clear();
18958  // We've hit a cycle.
18959  } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
18960  Current.count(TCanonical)) {
18961  // If we haven't diagnosed this cycle yet, do so now.
18962  if (!Invalid.count(TCanonical)) {
18963  S.Diag((*Ctor->init_begin())->getSourceLocation(),
18964  diag::warn_delegating_ctor_cycle)
18965  << Ctor;
18966 
18967  // Don't add a note for a function delegating directly to itself.
18968  if (TCanonical != Canonical)
18969  S.Diag(Target->getLocation(), diag::note_it_delegates_to);
18970 
18972  while (C->getCanonicalDecl() != Canonical) {
18973  const FunctionDecl *FNTarget = nullptr;
18974  (void)C->getTargetConstructor()->hasBody(FNTarget);
18975  assert(FNTarget && "Ctor cycle through bodiless function");
18976 
18977  C = const_cast<CXXConstructorDecl*>(
18978  cast<CXXConstructorDecl>(FNTarget));
18979  S.Diag(C->getLocation(), diag::note_which_delegates_to);
18980  }
18981  }
18982 
18983  Invalid.insert(Current.begin(), Current.end());
18984  Current.clear();
18985  } else {
18986  DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
18987  }
18988 }
18989 
18990 
18992  llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
18993 
18994  for (DelegatingCtorDeclsType::iterator
18996  E = DelegatingCtorDecls.end();
18997  I != E; ++I)
18998  DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
18999 
19000  for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
19001  (*CI)->setInvalidDecl();
19002 }
19003 
19004 namespace {
19005  /// AST visitor that finds references to the 'this' expression.
19006  class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
19007  Sema &S;
19008 
19009  public:
19010  explicit FindCXXThisExpr(Sema &S) : S(S) { }
19011 
19012  bool VisitCXXThisExpr(CXXThisExpr *E) {
19013  S.Diag(E->getLocation(), diag::err_this_static_member_func)
19014  << E->isImplicit();
19015  return false;
19016  }
19017  };
19018 }
19019 
19021  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19022  if (!TSInfo)
19023  return false;
19024 
19025  TypeLoc TL = TSInfo->getTypeLoc();
19027  if (!ProtoTL)
19028  return false;
19029 
19030  // C++11 [expr.prim.general]p3:
19031  // [The expression this] shall not appear before the optional
19032  // cv-qualifier-seq and it shall not appear within the declaration of a
19033  // static member function (although its type and value category are defined
19034  // within a static member function as they are within a non-static member
19035  // function). [ Note: this is because declaration matching does not occur
19036  // until the complete declarator is known. - end note ]
19037  const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19038  FindCXXThisExpr Finder(*this);
19039 
19040  // If the return type came after the cv-qualifier-seq, check it now.
19041  if (Proto->hasTrailingReturn() &&
19042  !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
19043  return true;
19044 
19045  // Check the exception specification.
19047  return true;
19048 
19049  // Check the trailing requires clause
19050  if (Expr *E = Method->getTrailingRequiresClause())
19051  if (!Finder.TraverseStmt(E))
19052  return true;
19053 
19055 }
19056 
19058  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19059  if (!TSInfo)
19060  return false;
19061 
19062  TypeLoc TL = TSInfo->getTypeLoc();
19064  if (!ProtoTL)
19065  return false;
19066 
19067  const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19068  FindCXXThisExpr Finder(*this);
19069 
19070  switch (Proto->getExceptionSpecType()) {
19071  case EST_Unparsed:
19072  case EST_Uninstantiated:
19073  case EST_Unevaluated:
19074  case EST_BasicNoexcept:
19075  case EST_NoThrow:
19076  case EST_DynamicNone:
19077  case EST_MSAny:
19078  case EST_None:
19079  break;
19080 
19081  case EST_DependentNoexcept:
19082  case EST_NoexceptFalse:
19083  case EST_NoexceptTrue:
19084  if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
19085  return true;
19086  [[fallthrough]];
19087 
19088  case EST_Dynamic:
19089  for (const auto &E : Proto->exceptions()) {
19090  if (!Finder.TraverseType(E))
19091  return true;
19092  }
19093  break;
19094  }
19095 
19096  return false;
19097 }
19098 
19100  FindCXXThisExpr Finder(*this);
19101 
19102  // Check attributes.
19103  for (const auto *A : Method->attrs()) {
19104  // FIXME: This should be emitted by tblgen.
19105  Expr *Arg = nullptr;
19106  ArrayRef<Expr *> Args;
19107  if (const auto *G = dyn_cast<GuardedByAttr>(A))
19108  Arg = G->getArg();
19109  else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
19110  Arg = G->getArg();
19111  else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
19112  Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
19113  else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
19114  Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
19115  else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
19116  Arg = ETLF->getSuccessValue();
19117  Args = llvm::ArrayRef(ETLF->args_begin(), ETLF->args_size());
19118  } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
19119  Arg = STLF->getSuccessValue();
19120  Args = llvm::ArrayRef(STLF->args_begin(), STLF->args_size());
19121  } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
19122  Arg = LR->getArg();
19123  else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
19124  Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
19125  else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
19126  Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19127  else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
19128  Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19129  else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
19130  Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19131  else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
19132  Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19133 
19134  if (Arg && !Finder.TraverseStmt(Arg))
19135  return true;
19136 
19137  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
19138  if (!Finder.TraverseStmt(Args[I]))
19139  return true;
19140  }
19141  }
19142 
19143  return false;
19144 }
19145 
19147  bool IsTopLevel, ExceptionSpecificationType EST,
19148  ArrayRef<ParsedType> DynamicExceptions,
19149  ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
19150  SmallVectorImpl<QualType> &Exceptions,
19152  Exceptions.clear();
19153  ESI.Type = EST;
19154  if (EST == EST_Dynamic) {
19155  Exceptions.reserve(DynamicExceptions.size());
19156  for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
19157  // FIXME: Preserve type source info.
19158  QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
19159 
19160  if (IsTopLevel) {
19162  collectUnexpandedParameterPacks(ET, Unexpanded);
19163  if (!Unexpanded.empty()) {
19165  DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
19166  Unexpanded);
19167  continue;
19168  }
19169  }
19170 
19171  // Check that the type is valid for an exception spec, and
19172  // drop it if not.
19173  if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
19174  Exceptions.push_back(ET);
19175  }
19176  ESI.Exceptions = Exceptions;
19177  return;
19178  }
19179 
19180  if (isComputedNoexcept(EST)) {
19181  assert((NoexceptExpr->isTypeDependent() ||
19182  NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
19183  Context.BoolTy) &&
19184  "Parser should have made sure that the expression is boolean");
19185  if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
19186  ESI.Type = EST_BasicNoexcept;
19187  return;
19188  }
19189 
19190  ESI.NoexceptExpr = NoexceptExpr;
19191  return;
19192  }
19193 }
19194 
19197  SourceRange SpecificationRange,
19198  ArrayRef<ParsedType> DynamicExceptions,
19199  ArrayRef<SourceRange> DynamicExceptionRanges,
19200  Expr *NoexceptExpr) {
19201  if (!MethodD)
19202  return;
19203 
19204  // Dig out the method we're referring to.
19205  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
19206  MethodD = FunTmpl->getTemplatedDecl();
19207 
19208  CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
19209  if (!Method)
19210  return;
19211 
19212  // Check the exception specification.
19213  llvm::SmallVector<QualType, 4> Exceptions;
19215  checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
19216  DynamicExceptionRanges, NoexceptExpr, Exceptions,
19217  ESI);
19218 
19219  // Update the exception specification on the function type.
19220  Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
19221 
19222  if (Method->isStatic())
19224 
19225  if (Method->isVirtual()) {
19226  // Check overrides, which we previously had to delay.
19227  for (const CXXMethodDecl *O : Method->overridden_methods())
19229  }
19230 }
19231 
19232 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
19233 ///
19235  SourceLocation DeclStart, Declarator &D,
19236  Expr *BitWidth,
19237  InClassInitStyle InitStyle,
19238  AccessSpecifier AS,
19239  const ParsedAttr &MSPropertyAttr) {
19240  const IdentifierInfo *II = D.getIdentifier();
19241  if (!II) {
19242  Diag(DeclStart, diag::err_anonymous_property);
19243  return nullptr;
19244  }
19245  SourceLocation Loc = D.getIdentifierLoc();
19246 
19248  QualType T = TInfo->getType();
19249  if (getLangOpts().CPlusPlus) {
19251 
19254  D.setInvalidType();
19255  T = Context.IntTy;
19256  TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19257  }
19258  }
19259 
19261 
19262  if (D.getDeclSpec().isInlineSpecified())
19263  Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19264  << getLangOpts().CPlusPlus17;
19267  diag::err_invalid_thread)
19268  << DeclSpec::getSpecifierName(TSCS);
19269 
19270  // Check to see if this name was declared as a member previously
19271  NamedDecl *PrevDecl = nullptr;
19272  LookupResult Previous(*this, II, Loc, LookupMemberName,
19274  LookupName(Previous, S);
19275  switch (Previous.getResultKind()) {
19276  case LookupResult::Found:
19278  PrevDecl = Previous.getAsSingle<NamedDecl>();
19279  break;
19280 
19282  PrevDecl = Previous.getRepresentativeDecl();
19283  break;
19284 
19288  break;
19289  }
19290 
19291  if (PrevDecl && PrevDecl->isTemplateParameter()) {
19292  // Maybe we will complain about the shadowed template parameter.
19294  // Just pretend that we didn't see the previous declaration.
19295  PrevDecl = nullptr;
19296  }
19297 
19298  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19299  PrevDecl = nullptr;
19300 
19301  SourceLocation TSSL = D.getBeginLoc();
19302  MSPropertyDecl *NewPD =
19303  MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
19304  MSPropertyAttr.getPropertyDataGetter(),
19305  MSPropertyAttr.getPropertyDataSetter());
19306  ProcessDeclAttributes(TUScope, NewPD, D);
19307  NewPD->setAccess(AS);
19308 
19309  if (NewPD->isInvalidDecl())
19310  Record->setInvalidDecl();
19311 
19313  NewPD->setModulePrivate();
19314 
19315  if (NewPD->isInvalidDecl() && PrevDecl) {
19316  // Don't introduce NewFD into scope; there's already something
19317  // with the same name in the same scope.
19318  } else if (II) {
19319  PushOnScopeChains(NewPD, S);
19320  } else
19321  Record->addDecl(NewPD);
19322 
19323  return NewPD;
19324 }
19325 
19327  Declarator &Declarator, unsigned TemplateParameterDepth) {
19328  auto &Info = InventedParameterInfos.emplace_back();
19329  TemplateParameterList *ExplicitParams = nullptr;
19330  ArrayRef<TemplateParameterList *> ExplicitLists =
19332  if (!ExplicitLists.empty()) {
19333  bool IsMemberSpecialization, IsInvalid;
19334  ExplicitParams = MatchTemplateParametersToScopeSpecifier(
19336  Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
19337  ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
19338  /*SuppressDiagnostic=*/true);
19339  }
19340  // C++23 [dcl.fct]p23:
19341  // An abbreviated function template can have a template-head. The invented
19342  // template-parameters are appended to the template-parameter-list after
19343  // the explicitly declared template-parameters.
19344  //
19345  // A template-head must have one or more template-parameters (read:
19346  // 'template<>' is *not* a template-head). Only append the invented
19347  // template parameters if we matched the nested-name-specifier to a non-empty
19348  // TemplateParameterList.
19349  if (ExplicitParams && !ExplicitParams->empty()) {
19350  Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
19351  llvm::append_range(Info.TemplateParams, *ExplicitParams);
19352  Info.NumExplicitTemplateParams = ExplicitParams->size();
19353  } else {
19354  Info.AutoTemplateParameterDepth = TemplateParameterDepth;
19355  Info.NumExplicitTemplateParams = 0;
19356  }
19357 }
19358 
19360  auto &FSI = InventedParameterInfos.back();
19361  if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
19362  if (FSI.NumExplicitTemplateParams != 0) {
19363  TemplateParameterList *ExplicitParams =
19367  Context, ExplicitParams->getTemplateLoc(),
19368  ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
19369  ExplicitParams->getRAngleLoc(),
19370  ExplicitParams->getRequiresClause()));
19371  } else {
19374  Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
19375  SourceLocation(), /*RequiresClause=*/nullptr));
19376  }
19377  }
19378  InventedParameterInfos.pop_back();
19379 }
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3278
NodeId Parent
Definition: ASTDiff.cpp:191
int Depth
Definition: ASTDiff.cpp:190
This file provides some common utility functions for processing Lambda related AST Constructs.
DynTypedNode Node
StringRef P
static char ID
Definition: Arena.cpp:183
llvm::APSInt APSInt
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
int Category
Definition: Format.cpp:2975
LangStandard::Kind Std
llvm::MachO::Target Target
Definition: MachO.h:48
llvm::MachO::Record Record
Definition: MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
@ ForExternalRedeclaration
The lookup results will be used for redeclaration of a name with external linkage; non-visible lookup...
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
This file declares semantic analysis for CUDA constructs.
static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, SourceLocation CurrentLocation)
Check if we're implicitly defining a move assignment operator for a class with virtual bases.
static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID)
static void DelegatingCycleHelper(CXXConstructorDecl *Ctor, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Valid, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Invalid, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Current, Sema &S)
static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *Body, Sema::CheckConstexprKind Kind)
Check the body for the given constexpr function declaration only contains the permitted types of stat...
llvm::SmallPtrSet< QualType, 4 > IndirectBaseSet
Use small set to collect indirect bases.
static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, CXXRecordDecl *Class)
static bool checkVectorDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const VectorType *VT)
static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind, SourceLocation Loc, QualType T, unsigned DiagID, Ts &&...DiagArgs)
Check that the given type is a literal type.
static void SearchForReturnInStmt(Sema &Self, Stmt *S)
static void extendRight(SourceRange &R, SourceRange After)
static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, SourceLocation Loc, IdentifierInfo *II, bool *IsInline, NamespaceDecl *PrevNS)
Diagnose a mismatch in 'inline' qualifiers when a namespace is reopened.
static bool RefersToRValueRef(Expr *MemRef)
static ClassTemplateDecl * LookupStdInitializerList(Sema &S, SourceLocation Loc)
static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy)
static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base)
Determine whether a direct base class is a virtual base class.
static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, llvm::APSInt &Size)
#define CheckPolymorphic(Type)
static bool findCircularInheritance(const CXXRecordDecl *Class, const CXXRecordDecl *Current)
Determine whether the given class is a base class of the given class, including looking at dependent ...
static void BuildBasePathArray(const CXXBasePath &Path, CXXCastPath &BasePathArray)
static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy, unsigned TyWidth, SmallVectorImpl< char > &Str)
Convert character's value, interpreted as a code unit, to a string.
static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, QualType SubType, bool ConstRHS, CXXSpecialMemberKind CSM, TrivialSubobjectKind Kind, Sema::TrivialABIHandling TAH, bool Diagnose)
Check whether the special member selected for a given type would be trivial.
static void CheckAbstractClassUsage(AbstractUsageInfo &Info, FunctionDecl *FD)
Check for invalid uses of an abstract type in a function declaration.
static unsigned getRecordDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for record diagnostic message.
static const void * GetKeyForBase(ASTContext &Context, QualType BaseType)
static void extendLeft(SourceRange &R, SourceRange Before)
static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM, bool ConstArg, Sema::TrivialABIHandling TAH, bool Diagnose)
Check whether the members of a class type allow a special member to be trivial.
static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals, bool ConstRHS, CXXConstructorDecl *InheritedCtor=nullptr, Sema::InheritedConstructorInfo *Inherited=nullptr)
Is the special member function which would be selected to perform the specified operation on the spec...
static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, TargetInfo::CallingConvKind CCK)
Determine whether a type is permitted to be passed or returned in registers, per C++ [class....
static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, UnresolvedSetImpl &Operators, OverloadedOperatorKind Op)
Perform the unqualified lookups that might be needed to form a defaulted comparison function for the ...
static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS)
static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM, unsigned Quals, bool ConstRHS, Sema::TrivialABIHandling TAH, CXXMethodDecl **Selected)
Perform lookup for a special member of the specified kind, and determine whether it is trivial.
static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp)
Diagnose an implicit copy operation for a class which is odr-used, but which is deprecated because th...
static void AddMostOverridenMethods(const CXXMethodDecl *MD, llvm::SmallPtrSetImpl< const CXXMethodDecl * > &Methods)
Add the most overridden methods from MD to Methods.
static bool CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, CanQualType ExpectedResultType, CanQualType ExpectedFirstParamType, unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag)
static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, const CXXRecordDecl *RD, CXXCastPath &BasePath)
Find the base class to decompose in a built-in decomposition of a class type.
static Sema::ImplicitExceptionSpecification ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD, Sema::DefaultedComparisonKind DCK)
static StmtResult buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &To, const ExprBuilder &From, bool CopyingBaseSubobject, bool Copying, unsigned Depth=0)
Builds a statement that copies/moves the given entity from From to To.
static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, CXXRecordDecl *Class)
static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag, const CXXCtorInitializer *Previous, const CXXCtorInitializer *Current)
static bool BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, ImplicitInitializerKind ImplicitInitKind, CXXBaseSpecifier *BaseSpec, bool IsInheritedVirtualBase, CXXCtorInitializer *&CXXBaseInit)
static bool checkTupleLikeDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, VarDecl *Src, QualType DecompType, const llvm::APSInt &TupleSize)
static void NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, const QualType &Type)
Recursively add the bases of Type. Don't add Type itself.
static bool CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, SmallVectorImpl< SourceLocation > &ReturnStmts, SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, SourceLocation &Cxx2bLoc, Sema::CheckConstexprKind Kind)
Check the provided statement is allowed in a constexpr function definition.
static bool functionDeclHasDefaultArgument(const FunctionDecl *FD)
static bool CheckConstexprParameterTypes(Sema &SemaRef, const FunctionDecl *FD, Sema::CheckConstexprKind Kind)
Check whether a function's parameter types are all literal types.
static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext)
Determine whether a using statement is in a context where it will be apply in all contexts.
static bool checkMemberDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const CXXRecordDecl *OrigRD)
static CXXConstructorDecl * findUserDeclaredCtor(CXXRecordDecl *RD)
static Expr * CastForMoving(Sema &SemaRef, Expr *E)
static void checkForMultipleExportedDefaultConstructors(Sema &S, CXXRecordDecl *Class)
static bool isNonlocalVariable(const Decl *D)
Determine whether the given declaration is a global variable or static data member.
static bool checkSimpleDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, llvm::function_ref< ExprResult(SourceLocation, Expr *, unsigned)> GetInit)
static TemplateArgumentLoc getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T)
static void findImplicitlyDeclaredEqualityComparisons(ASTContext &Ctx, CXXRecordDecl *RD, llvm::SmallVectorImpl< FunctionDecl * > &Spaceships)
Find the equality comparison functions that should be implicitly declared in a given class definition...
static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl< const void * > &IdealInits)
ImplicitInitializerKind
ImplicitInitializerKind - How an implicit base or member initializer should initialize its base or me...
@ IIK_Default
@ IIK_Move
@ IIK_Inherit
@ IIK_Copy
static bool ConvertAPValueToString(const APValue &V, QualType T, SmallVectorImpl< char > &Str, ASTContext &Context)
Convert \V to a string we can present to the user in a diagnostic \T is the type of the expression th...
static bool checkArrayDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const ConstantArrayType *CAT)
static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class)
static bool UsefulToPrintExpr(const Expr *E)
Some Expression types are not useful to print notes about, e.g.
static bool FindBaseInitializer(Sema &SemaRef, CXXRecordDecl *ClassDecl, QualType BaseType, const CXXBaseSpecifier *&DirectBaseSpec, const CXXBaseSpecifier *&VirtualBaseSpec)
Find the direct and/or virtual base specifiers that correspond to the given base type,...
static bool checkLiteralOperatorTemplateParameterList(Sema &SemaRef, FunctionTemplateDecl *TpDecl)
static bool CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl)
static bool ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, llvm::function_ref< bool(const CXXMethodDecl *)> Report)
Report an error regarding overriding, along with any relevant overridden methods.
static bool CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl)
static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, TemplateArgumentListInfo &Args, const TemplateParameterList *Params)
static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, Sema::CheckConstexprKind Kind)
Check whether a function's return type is a literal type.
static void DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, const CXXConstructorDecl *Constructor, ArrayRef< CXXCtorInitializer * > Inits)
static Sema::ImplicitExceptionSpecification computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD)
static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T)
Determine whether the given type is an incomplete or zero-lenfgth array type.
static CXXBaseSpecifier * findDirectBaseWithType(CXXRecordDecl *Derived, QualType DesiredBase, bool &AnyDependentBases)
Find the base specifier for a base class with the given type.
TrivialSubobjectKind
The kind of subobject we are checking for triviality.
@ TSK_CompleteObject
The object is actually the complete object.
@ TSK_Field
The subobject is a non-static data member.
@ TSK_BaseClass
The subobject is a base class.
static bool hasOneRealArgument(MultiExprArg Args)
Determine whether the given list arguments contains exactly one "real" (non-default) argument.
static StmtResult buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &ToB, const ExprBuilder &FromB)
When generating a defaulted copy or move assignment operator, if a field should be copied with __buil...
static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, SourceLocation DefaultLoc)
static bool BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, ImplicitInitializerKind ImplicitInitKind, FieldDecl *Field, IndirectFieldDecl *Indirect, CXXCtorInitializer *&CXXMemberInit)
static NamespaceDecl * getNamespaceDecl(NamedDecl *D)
getNamespaceDecl - Returns the namespace a decl represents.
static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, FieldDecl *Field, IndirectFieldDecl *Indirect=nullptr)
static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(Sema &S, CXXRecordDecl *Class, CXXSpecialMemberKind CSM, unsigned FieldQuals, bool ConstRHS)
Look up the special member function that would be called by a special member function for a subobject...
static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg, CXXConstructorDecl *InheritedCtor=nullptr, Sema::InheritedConstructorInfo *Inherited=nullptr)
Determine whether the specified special member function would be constexpr if it were implicitly defi...
static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, SourceLocation Loc, StringRef Trait, TemplateArgumentListInfo &Args, unsigned DiagID)
static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected, Sema &S)
static StmtResult buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &To, const ExprBuilder &From, bool CopyingBaseSubobject, bool Copying)
static const void * GetKeyForMember(ASTContext &Context, CXXCtorInitializer *Member)
static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, CXXMethodDecl *MD)
static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, unsigned I, QualType T)
static Sema::ImplicitExceptionSpecification ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD, CXXSpecialMemberKind CSM, Sema::InheritedConstructorInfo *ICI)
static bool checkComplexDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const ComplexType *CT)
static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident)
static bool InitializationHasSideEffects(const FieldDecl &FD)
static bool CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, const FunctionDecl *FnDecl)
static bool checkArrayLikeDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType)
static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, DeclStmt *DS, SourceLocation &Cxx1yLoc, Sema::CheckConstexprKind Kind)
Check the given declaration statement is legal within a constexpr function body.
static bool IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2)
Determine whether a using declaration considers the given declarations as "equivalent",...
static TemplateArgumentLoc getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, uint64_t I)
static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, const CXXDestructorDecl *DD, Sema::CheckConstexprKind Kind)
Determine whether a destructor cannot be constexpr due to.
static bool CheckConstexprCtorInitializer(Sema &SemaRef, const FunctionDecl *Dcl, FieldDecl *Field, llvm::SmallSet< Decl *, 16 > &Inits, bool &Diagnosed, Sema::CheckConstexprKind Kind)
Check that the given field is initialized within a constexpr constructor.
static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record, const BaseSet &Bases)
Determines if the given class is provably not derived from all of the prospective base classes.
This file declares semantic analysis for OpenMP constructs and clauses.
target
Definition: SemaSYCL.cpp:45
This file declares semantic analysis for SYCL constructs.
static bool isInvalid(LocType Loc, bool *Invalid)
Defines various enumerations that describe declaration and type specifiers.
Defines the clang::TypeLoc interface and its subclasses.
Allows QualTypes to be sorted and hence used in maps and sets.
const NestedNameSpecifier * Specifier
StateNode * Previous
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
__device__ int
std::pair< CXXConstructorDecl *, bool > findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const
Find the constructor to use for inherited construction of a base class, and whether that base class c...
InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, ConstructorUsingShadowDecl *Shadow)
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
virtual void HandleVTable(CXXRecordDecl *RD)
Callback involved at the end of a translation unit to notify the consumer that a vtable for the given...
Definition: ASTConsumer.h:123
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:18
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:697
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
unsigned getIntWidth(QualType T) const
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:648
QualType getRecordType(const RecordDecl *Decl) const
unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built.
Definition: ASTContext.h:3228
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2568
unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
Definition: ASTContext.h:3242
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2584
CanQualType LongDoubleTy
Definition: ASTContext.h:1103
CanQualType Char16Ty
Definition: ASTContext.h:1098
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
CanQualType VoidPtrTy
Definition: ASTContext.h:1118
void Deallocate(void *Ptr) const
Definition: ASTContext.h:724
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1119
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1594
CanQualType WideCharTy
Definition: ASTContext.h:1095
IdentifierTable & Idents
Definition: ASTContext.h:644
QualType getConstType(QualType T) const
Return the uniqued reference to the type for a const qualified type.
Definition: ASTContext.h:1302
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2761
const LangOptions & getLangOpts() const
Definition: ASTContext.h:775
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
Definition: ASTContext.h:2265
QualType AutoDeductTy
Definition: ASTContext.h:1152
CanQualType BoolTy
Definition: ASTContext.h:1092
unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built.
Definition: ASTContext.h:3207
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y) const
Determine whether the given template names refer to the same template.
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType CharTy
Definition: ASTContext.h:1093
unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
Definition: ASTContext.h:3221
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
Definition: ASTContext.h:3214
CanQualType IntTy
Definition: ASTContext.h:1100
unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
Definition: ASTContext.h:3238
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2160
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated,...
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2611
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2334
CanQualType BuiltinFnTy
Definition: ASTContext.h:1120
unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
Definition: ASTContext.h:3203
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
unsigned NumImplicitMoveAssignmentOperatorsDeclared
The number of implicitly-declared move assignment operators for which declarations were built.
Definition: ASTContext.h:3235
CanQualType VoidTy
Definition: ASTContext.h:1091
unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
Definition: ASTContext.h:3217
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
QualType getExceptionObjectType(QualType T) const
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1102
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1572
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:757
llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const
Make an APSInt of the appropriate width and signedness for the given Value and integer Type.
Definition: ASTContext.h:3019
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1192
CanQualType Char32Ty
Definition: ASTContext.h:1099
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
Definition: ASTContext.h:3210
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
unsigned NumImplicitCopyAssignmentOperators
The number of implicitly-declared copy assignment operators.
Definition: ASTContext.h:3224
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
NestedNameSpecifier * getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
CanQualType Char8Ty
Definition: ASTContext.h:1097
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1073
unsigned NumImplicitMoveAssignmentOperators
The number of implicitly-declared move assignment operators.
Definition: ASTContext.h:3231
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
Represents an access specifier followed by colon ':'.
Definition: DeclCXX.h:86
static AccessSpecDecl * Create(ASTContext &C, AccessSpecifier AS, DeclContext *DC, SourceLocation ASLoc, SourceLocation ColonLoc)
Definition: DeclCXX.h:117
bool isUnset() const
Definition: Ownership.h:167
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Wrapper for source info for arrays.
Definition: TypeLoc.h:1561
TypeLoc getElementLoc() const
Definition: TypeLoc.h:1591
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3318
QualType getElementType() const
Definition: Type.h:3330
Attr - This represents one attribute.
Definition: Attr.h:46
Attr * clone(ASTContext &C) const
attr::Kind getKind() const
Definition: Attr.h:92
bool isInherited() const
Definition: Attr.h:101
SourceLocation getLocation() const
Definition: Attr.h:99
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:5781
AutoTypeKeyword getKeyword() const
Definition: Type.h:5812
Represents a C++ declaration that introduces decls from somewhere else.
Definition: DeclCXX.h:3414
unsigned shadow_size() const
Return the number of shadowed declarations associated with this using declaration.
Definition: DeclCXX.h:3492
void addShadowDecl(UsingShadowDecl *S)
Definition: DeclCXX.cpp:3139
shadow_iterator shadow_begin() const
Definition: DeclCXX.h:3484
void removeShadowDecl(UsingShadowDecl *S)
Definition: DeclCXX.cpp:3148
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4293
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3892
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4838
static bool isCompoundAssignmentOp(Opcode Opc)
Definition: Expr.h:4032
Opcode getOpcode() const
Definition: Expr.h:3936
Expr * getRHS() const
Definition: Expr.h:3943
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition: Expr.cpp:2198
Expr * getLHS() const
Definition: Expr.h:3941
A binding in a decomposition declaration.
Definition: DeclCXX.h:4104
static BindingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id)
Definition: DeclCXX.cpp:3330
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6214
Wrapper for source info for block pointers.
Definition: TypeLoc.h:1314
This class is used for builtin types like 'int'.
Definition: Type.h:2777
Kind getKind() const
Definition: Type.h:2823
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
DeclContext::lookup_iterator Decls
The declarations found inside this base class subobject.
AccessSpecifier Access
The access along this inheritance path.
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
std::list< CXXBasePath >::iterator paths_iterator
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclCXX.h:194
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition: DeclCXX.h:203
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:249
SourceRange getSourceRange() const LLVM_READONLY
Retrieves the source range that contains the entire base specifier.
Definition: DeclCXX.h:193
AccessSpecifier getAccessSpecifier() const
Returns the access specifier for this base specifier.
Definition: DeclCXX.h:230
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:720
CXXCatchStmt - This represents a C++ catch block.
Definition: StmtCXX.h:28
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1540
static CXXConstructExpr * Create(const ASTContext &Ctx, QualType Ty, SourceLocation Loc, CXXConstructorDecl *Ctor, bool Elidable, ArrayRef< Expr * > Args, bool HadMultipleCandidates, bool ListInitialization, bool StdInitListInitialization, bool ZeroInitialization, CXXConstructionKind ConstructKind, SourceRange ParenOrBraceRange)
Create a C++ construction expression.
Definition: ExprCXX.cpp:1110
bool isImmediateEscalating() const
Definition: ExprCXX.h:1698
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1683
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1603
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2532
bool isMoveConstructor(unsigned &TypeQuals) const
Determine whether this constructor is a move constructor (C++11 [class.copy]p3), which can be used to...
Definition: DeclCXX.cpp:2765
ExplicitSpecifier getExplicitSpecifier()
Definition: DeclCXX.h:2603
init_iterator init_begin()
Retrieve an iterator to the first initializer.
Definition: DeclCXX.h:2628
CXXConstructorDecl * getTargetConstructor() const
When this constructor delegates to another, retrieve the target.
Definition: DeclCXX.cpp:2742
bool isCopyConstructor(unsigned &TypeQuals) const
Whether this constructor is a copy constructor (C++ [class.copy]p2, which can be used to copy the cla...
Definition: DeclCXX.cpp:2760
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:2751
InheritedConstructor getInheritedConstructor() const
Get the constructor that this inheriting constructor is based on.
Definition: DeclCXX.h:2769
static CXXConstructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited=InheritedConstructor(), Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2721
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2774
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2859
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2899
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2297
bool isWritten() const
Determine whether this initializer is explicitly written in the source code.
Definition: DeclCXX.h:2469
FieldDecl * getAnyMember() const
Definition: DeclCXX.h:2443
SourceRange getSourceRange() const LLVM_READONLY
Determine the source range covering the entire initializer.
Definition: DeclCXX.cpp:2670
SourceLocation getSourceLocation() const
Determine the source location of the initializer.
Definition: DeclCXX.cpp:2657
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1371
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2796
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2855
A mapping from each virtual member function to its set of final overriders.
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition: ExprCXX.h:1731
Represents a call to a member function that may be written either with member call syntax (e....
Definition: ExprCXX.h:176
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Definition: ExprCXX.cpp:673
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2057
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition: DeclCXX.cpp:2453
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition: DeclCXX.cpp:2460
bool isVirtual() const
Definition: DeclCXX.h:2112
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2183
unsigned getNumExplicitParams() const
Definition: DeclCXX.h:2211
bool isVolatile() const
Definition: DeclCXX.h:2110
overridden_method_range overridden_methods() const
Definition: DeclCXX.cpp:2532
unsigned size_overridden_methods() const
Definition: DeclCXX.cpp:2526
CXXMethodDecl * getMostRecentDecl()
Definition: DeclCXX.h:2160
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:2233
method_iterator begin_overridden_methods() const
Definition: DeclCXX.cpp:2516
bool isInstance() const
Definition: DeclCXX.h:2084
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2486
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2273
QualType getFunctionObjectParameterType() const
Definition: DeclCXX.h:2207
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2153
bool isStatic() const
Definition: DeclCXX.cpp:2185
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2464
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:765
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:81
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool hasConstexprDefaultConstructor() const
Determine whether this class has a constexpr default constructor.
Definition: DeclCXX.h:1270
friend_range friends() const
Definition: DeclFriend.h:246
bool hasTrivialMoveAssignment() const
Determine whether this class has a trivial move assignment operator (C++11 [class....
Definition: DeclCXX.h:1341
bool isTriviallyCopyable() const
Determine whether this class is considered trivially copyable per (C++11 [class]p6).
Definition: DeclCXX.cpp:575
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1240
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition: DeclCXX.cpp:1563
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1366
bool hasUserDeclaredDestructor() const
Determine whether this class has a user-declared destructor.
Definition: DeclCXX.h:1004
bool implicitCopyConstructorHasConstParam() const
Determine whether an implicit copy constructor for this type would have a parameter with a const-qual...
Definition: DeclCXX.h:830
bool defaultedDestructorIsDeleted() const
true if a defaulted destructor for this class would be deleted.
Definition: DeclCXX.h:724
bool hasInheritedAssignment() const
Determine whether this class has a using-declaration that names a base class assignment operator.
Definition: DeclCXX.h:1420
bool allowConstDefaultInit() const
Determine whether declaring a const variable with this type is ok per core issue 253.
Definition: DeclCXX.h:1391
bool hasTrivialDestructorForCall() const
Definition: DeclCXX.h:1370
bool defaultedMoveConstructorIsDeleted() const
true if a defaulted move constructor for this class would be deleted.
Definition: DeclCXX.h:716
bool isLiteral() const
Determine whether this class is a literal type.
Definition: DeclCXX.cpp:1389
bool hasUserDeclaredMoveAssignment() const
Determine whether this class has had a move assignment declared by the user.
Definition: DeclCXX.h:964
bool defaultedDestructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition: DeclCXX.h:1356
base_class_range bases()
Definition: DeclCXX.h:618
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition: DeclCXX.cpp:568
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1021
bool hasTrivialMoveConstructor() const
Determine whether this class has a trivial move constructor (C++11 [class.copy]p12)
Definition: DeclCXX.h:1301
bool needsImplicitDefaultConstructor() const
Determine if we need to declare a default constructor for this class.
Definition: DeclCXX.h:776
bool needsImplicitMoveConstructor() const
Determine whether this class should get an implicit move constructor or if any existing special membe...
Definition: DeclCXX.h:895
bool hasUserDeclaredCopyAssignment() const
Determine whether this class has a user-declared copy assignment operator.
Definition: DeclCXX.h:913
method_range methods() const
Definition: DeclCXX.h:660
bool needsOverloadResolutionForCopyAssignment() const
Determine whether we need to eagerly declare a defaulted copy assignment operator for this class.
Definition: DeclCXX.h:934
static AccessSpecifier MergeAccess(AccessSpecifier PathAccess, AccessSpecifier DeclAccess)
Calculates the access of a decl that is reached along a path.
Definition: DeclCXX.h:1722
bool defaultedDefaultConstructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition: DeclCXX.h:1263
bool hasTrivialCopyConstructor() const
Determine whether this class has a trivial copy constructor (C++ [class.copy]p6, C++11 [class....
Definition: DeclCXX.h:1278
void setImplicitMoveAssignmentIsDeleted()
Set that we attempted to declare an implicit move assignment operator, but overload resolution failed...
Definition: DeclCXX.h:976
bool hasConstexprDestructor() const
Determine whether this class has a constexpr destructor.
Definition: DeclCXX.cpp:563
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition: DeclCXX.h:1214
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:612
bool defaultedCopyConstructorIsDeleted() const
true if a defaulted copy constructor for this class would be deleted.
Definition: DeclCXX.h:707
bool hasTrivialCopyConstructorForCall() const
Definition: DeclCXX.h:1282
bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths, bool LookupInDependent=false) const
Look for entities within the base classes of this C++ class, transitively searching all base class su...
bool lambdaIsDefaultConstructibleAndAssignable() const
Determine whether this lambda should have an implicit default constructor and copy and move assignmen...
Definition: DeclCXX.cpp:691
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1904
bool hasTrivialCopyAssignment() const
Determine whether this class has a trivial copy assignment operator (C++ [class.copy]p11,...
Definition: DeclCXX.h:1328
base_class_range vbases()
Definition: DeclCXX.h:635
base_class_iterator vbases_begin()
Definition: DeclCXX.h:642
ctor_range ctors() const
Definition: DeclCXX.h:680
void setImplicitMoveConstructorIsDeleted()
Set that we attempted to declare an implicit move constructor, but overload resolution failed so we d...
Definition: DeclCXX.h:877
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition: DeclCXX.h:1221
bool hasVariantMembers() const
Determine whether this class has any variant members.
Definition: DeclCXX.h:1236
void setImplicitCopyConstructorIsDeleted()
Set that we attempted to declare an implicit copy constructor, but overload resolution failed so we d...
Definition: DeclCXX.h:868
bool isDynamicClass() const
Definition: DeclCXX.h:584
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition: DeclCXX.h:1151
bool needsImplicitCopyConstructor() const
Determine whether this class needs an implicit copy constructor to be lazily declared.
Definition: DeclCXX.h:809
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
Definition: DeclCXX.h:1402
bool hasNonTrivialCopyConstructorForCall() const
Definition: DeclCXX.h:1293
bool hasDirectFields() const
Determine whether this class has direct non-static data members.
Definition: DeclCXX.h:1207
bool hasUserDeclaredCopyConstructor() const
Determine whether this class has a user-declared copy constructor.
Definition: DeclCXX.h:803
bool hasDefinition() const
Definition: DeclCXX.h:571
void setImplicitCopyAssignmentIsDeleted()
Set that we attempted to declare an implicit copy assignment operator, but overload resolution failed...
Definition: DeclCXX.h:919
bool needsImplicitDestructor() const
Determine whether this class needs an implicit destructor to be lazily declared.
Definition: DeclCXX.h:1010
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1896
void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const
Retrieve the final overriders for each virtual member function in the class hierarchy where this clas...
bool needsOverloadResolutionForMoveConstructor() const
Determine whether we need to eagerly declare a defaulted move constructor for this class.
Definition: DeclCXX.h:905
bool needsOverloadResolutionForMoveAssignment() const
Determine whether we need to eagerly declare a move assignment operator for this class.
Definition: DeclCXX.h:997
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:1974
bool hasNonTrivialDestructorForCall() const
Definition: DeclCXX.h:1380
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:523
bool needsOverloadResolutionForDestructor() const
Determine whether we need to eagerly declare a destructor for this class.
Definition: DeclCXX.h:1016
bool hasInheritedConstructor() const
Determine whether this class has a using-declaration that names a user-declared base class constructo...
Definition: DeclCXX.h:1414
CXXMethodDecl * getLambdaStaticInvoker() const
Retrieve the lambda static invoker, the address of which is returned by the conversion operator,...
Definition: DeclCXX.cpp:1605
bool needsOverloadResolutionForCopyConstructor() const
Determine whether we need to eagerly declare a defaulted copy constructor for this class.
Definition: DeclCXX.h:815
bool hasUserDeclaredMoveConstructor() const
Determine whether this class has had a move constructor declared by the user.
Definition: DeclCXX.h:856
bool needsImplicitMoveAssignment() const
Determine whether this class should get an implicit move assignment operator or if any existing speci...
Definition: DeclCXX.h:986
bool isInterfaceLike() const
Definition: DeclCXX.cpp:2003
bool needsImplicitCopyAssignment() const
Determine whether this class needs an implicit copy assignment operator to be lazily declared.
Definition: DeclCXX.h:928
bool hasTrivialMoveConstructorForCall() const
Definition: DeclCXX.h:1306
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1593
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:633
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
bool implicitCopyAssignmentHasConstParam() const
Determine whether an implicit copy assignment operator for this type would have a parameter with a co...
Definition: DeclCXX.h:949
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:564
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:73
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:94
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:209
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:214
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:126
SourceRange getRange() const
Definition: DeclSpec.h:79
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:83
bool isSet() const
Deprecated.
Definition: DeclSpec.h:227
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:152
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:212
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:207
Represents the this expression in C++.
Definition: ExprCXX.h:1148
SourceLocation getBeginLoc() const
Definition: ExprCXX.h:1168
bool isImplicit() const
Definition: ExprCXX.h:1171
SourceLocation getLocation() const
Definition: ExprCXX.h:1165
CXXTryStmt - A C++ try block, including all handlers.
Definition: StmtCXX.h:69
CXXCatchStmt * getHandler(unsigned i)
Definition: StmtCXX.h:108
unsigned getNumHandlers() const
Definition: StmtCXX.h:107
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2872
bool isCallToStdMove() const
Definition: Expr.cpp:3562
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3063
arg_range arguments()
Definition: Expr.h:3111
Expr * getCallee()
Definition: Expr.h:3022
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:3042
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
CanProxy< U > getAs() const
Retrieve a canonical type pointer with a different static type, upcasting or downcasting as needed.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:83
CastKind getCastKind() const
Definition: Expr.h:3579
Expr * getSubExpr()
Definition: Expr.h:3585
static CharSourceRange getTokenRange(SourceRange R)
SourceLocation getBegin() const
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
Declaration of a class template.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
ClassTemplateDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this template.
Represents a class template specialization, which refers to a class template with a given set of temp...
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
const ComparisonCategoryInfo * lookupInfoForType(QualType Ty) const
const ComparisonCategoryInfo & getInfoForType(QualType Ty) const
Return the comparison category information as specified by getCategoryForType(Ty).
const ComparisonCategoryInfo * lookupInfo(ComparisonCategoryType Kind) const
Return the cached comparison category information for the specified 'Kind'.
static StringRef getCategoryString(ComparisonCategoryType Kind)
static StringRef getResultString(ComparisonCategoryResult Kind)
static std::vector< ComparisonCategoryResult > getPossibleResultsForType(ComparisonCategoryType Type)
Return the list of results which are valid for the specified comparison category type.
const CXXRecordDecl * Record
The declaration for the comparison category type from the standard library.
ComparisonCategoryType Kind
The Kind of the comparison category type.
const ValueInfo * getValueInfo(ComparisonCategoryResult ValueKind) const
Complex values, per C99 6.2.5p11.
Definition: Type.h:2886
QualType getElementType() const
Definition: Type.h:2896
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1606
body_range body()
Definition: Stmt.h:1664
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt * > Stmts, FPOptionsOverride FPFeatures, SourceLocation LB, SourceLocation RB)
Definition: Stmt.cpp:383
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4231
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:195
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3356
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3412
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
Represents a shadow constructor declaration introduced into a class by a C++11 using-declaration that...
Definition: DeclCXX.h:3595
const CXXRecordDecl * getParent() const
Returns the parent of this using shadow declaration, which is the class in which this is declared.
Definition: DeclCXX.h:3659
static ConstructorUsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, UsingDecl *Using, NamedDecl *Target, bool IsVirtual)
Definition: DeclCXX.cpp:3121
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
NamedDecl * getDecl() const
AccessSpecifier getAccess() const
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1371
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1438
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2193
bool isFileContext() const
Definition: DeclBase.h:2139
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:1975
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1264
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2068
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1784
bool isTranslationUnit() const
Definition: DeclBase.h:2144
bool isRecord() const
Definition: DeclBase.h:2148
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1920
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2084
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1617
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1698
decl_iterator decls_end() const
Definition: DeclBase.h:2326
bool isStdNamespace() const
Definition: DeclBase.cpp:1248
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2324
bool isFunctionOrMethod() const
Definition: DeclBase.h:2120
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
Definition: DeclBase.cpp:1319
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1334
void addHiddenDecl(Decl *D)
Add the declaration D to this context without modifying any lookup tables.
Definition: DeclBase.cpp:1672
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2061
DeclContext * getNonTransparentContext()
Definition: DeclBase.cpp:1345
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1554
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
ValueDecl * getDecl()
Definition: Expr.h:1328
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:551
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition: Expr.cpp:488
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition: Expr.h:1452
bool isImmediateEscalating() const
Definition: Expr.h:1462
Captures information about "declaration specifiers".
Definition: DeclSpec.h:246
bool isVirtualSpecified() const
Definition: DeclSpec.h:644
bool isModulePrivateSpecified() const
Definition: DeclSpec.h:825
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition: DeclSpec.h:687
bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec and return false if there was no error.
Definition: DeclSpec.cpp:641
void ClearStorageClassSpecs()
Definition: DeclSpec.h:511
TST getTypeSpecType() const
Definition: DeclSpec.h:533
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:506
SCS getStorageClassSpec() const
Definition: DeclSpec.h:497
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:571
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:570
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:612
Expr * getPackIndexingExpr() const
Definition: DeclSpec.h:556
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:650
SourceLocation getFriendSpecLoc() const
Definition: DeclSpec.h:823
ParsedType getRepAsType() const
Definition: DeclSpec.h:543
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:498
bool isFriendSpecifiedFirst() const
Definition: DeclSpec.h:821
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:869
SourceLocation getEllipsisLoc() const
Definition: DeclSpec.h:619
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:613
SourceRange getExplicitSpecRange() const
Definition: DeclSpec.h:651
bool isInlineSpecified() const
Definition: DeclSpec.h:633
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:614
bool SetTypeQual(TQ T, SourceLocation Loc)
Definition: DeclSpec.cpp:1013
void ClearConstexprSpec()
Definition: DeclSpec.h:837
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition: DeclSpec.cpp:558
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:507
Expr * getRepAsExpr() const
Definition: DeclSpec.h:551
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:616
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:645
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:832
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:578
void forEachQualifier(llvm::function_ref< void(TQ, StringRef, SourceLocation)> Handle)
This method calls the passed in handler on each qual being set.
Definition: DeclSpec.cpp:453
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:636
SourceLocation getUnalignedSpecLoc() const
Definition: DeclSpec.h:617
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:615
FriendSpecified isFriendSpecified() const
Definition: DeclSpec.h:817
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:647
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:833
static const TST TST_auto
Definition: DeclSpec.h:317
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition: Stmt.h:1497
decl_range decls()
Definition: Stmt.h:1545
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.h:1523
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:443
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1218
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:501
void addAttr(Attr *A)
Definition: DeclBase.cpp:975
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:601
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition: Decl.cpp:100
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:88
void clearIdentifierNamespace()
Clears the namespace of this declaration.
Definition: DeclBase.h:1206
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:545
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition: DeclBase.h:1211
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1209
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:227
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2741
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1053
bool isInvalidDecl() const
Definition: DeclBase.h:596
unsigned getIdentifierNamespace() const
Definition: DeclBase.h:881
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:970
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition: DeclBase.h:1161
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:510
SourceLocation getLocation() const
Definition: DeclBase.h:447
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:143
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:210
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:910
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:822
void setImplicit(bool I=true)
Definition: DeclBase.h:602
void setReferenced(bool R=true)
Definition: DeclBase.h:631
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:530
attr_range attrs() const
Definition: DeclBase.h:543
AccessSpecifier getAccess() const
Definition: DeclBase.h:515
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:439
void dropAttr()
Definition: DeclBase.h:564
bool hasAttr() const
Definition: DeclBase.h:585
@ VisibleWhenImported
This declaration has an owning module, and is visible when that module is imported.
void setModuleOwnershipKind(ModuleOwnershipKind MOK)
Set whether this declaration is hidden from name lookup.
Definition: DeclBase.h:873
T * getAttr() const
Definition: DeclBase.h:581
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:435
DeclContext * getDeclContext()
Definition: DeclBase.h:456
DeclarationName getCXXDestructorName(CanQualType Ty)
Returns the name of a C++ destructor for the given Type.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
DeclarationName getCXXConstructorName(CanQualType Ty)
Returns the name of a C++ constructor for the given Type.
The name of a declaration.
const IdentifierInfo * getCXXLiteralIdentifier() const
If this name is the name of a literal operator, retrieve the identifier associated with it.
std::string getAsString() const
Retrieve the human-readable string for this name.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
NameKind getNameKind() const
Determine what kind of name this is.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:771
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:847
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1989
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:823
unsigned getNumTemplateParameterLists() const
Definition: Decl.h:859
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:806
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:800
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1898
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition: DeclSpec.h:2454
ArrayRef< TemplateParameterList * > getTemplateParameterLists() const
The template parameter lists that preceded the declarator.
Definition: DeclSpec.h:2647
bool isDeclarationOfFunction() const
Determine whether the declaration that will be produced from this declaration will be a function.
Definition: DeclSpec.cpp:325
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition: DeclSpec.h:2052
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:2045
bool isFunctionDeclarationContext() const
Return true if this declaration appears in a context where a function declarator would be a function ...
Definition: DeclSpec.h:2508
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2334
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition: DeclSpec.h:2337
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition: DeclSpec.h:2060
type_object_range type_objects() const
Returns the range of type objects, from the identifier outwards.
Definition: DeclSpec.h:2409
bool hasGroupingParens() const
Definition: DeclSpec.h:2717
void setInvalidType(bool Val=true)
Definition: DeclSpec.h:2711
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2392
bool isRedeclaration() const
Definition: DeclSpec.h:2763
DeclaratorContext getContext() const
Definition: DeclSpec.h:2070
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:2081
bool isFunctionDefinition() const
Definition: DeclSpec.h:2735
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition: DeclSpec.h:2485
void setInventedTemplateParameterList(TemplateParameterList *Invented)
Sets the template parameter list generated from the explicit template parameters along with any inven...
Definition: DeclSpec.h:2654
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition: DeclSpec.h:2064
bool mayHaveDecompositionDeclarator() const
Return true if the context permits a C++17 decomposition declarator.
Definition: DeclSpec.h:2209
bool isInvalidType() const
Definition: DeclSpec.h:2712
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:2080
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition: DeclSpec.h:2066
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition: DeclSpec.h:2324
const IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2328
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2396
bool isStaticMember()
Returns true if this declares a static member.
Definition: DeclSpec.cpp:416
A decomposition declaration.
Definition: DeclCXX.h:4163
ArrayRef< BindingDecl * > bindings() const
Definition: DeclCXX.h:4195
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition: DeclSpec.h:1788
ArrayRef< Binding > bindings() const
Definition: DeclSpec.h:1826
SourceRange getSourceRange() const
Definition: DeclSpec.h:1834
SourceLocation getLSquareLoc() const
Definition: DeclSpec.h:1832
Represents a C++17 deduced template specialization type.
Definition: Type.h:5829
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2423
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2403
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2412
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine) ...
Definition: Diagnostic.h:1577
bool isLastDiagnosticIgnored() const
Determine whether the previous diagnostic was ignored.
Definition: Diagnostic.h:776
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:922
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2323
TypeLoc getNamedTypeLoc() const
Definition: TypeLoc.h:2361
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2337
static EmptyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:5633
RAII object that enters a new expression evaluation context.
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3299
Represents an enum.
Definition: Decl.h:3869
enumerator_range enumerators() const
Definition: Decl.h:4002
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5375
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1896
const Expr * getExpr() const
Definition: DeclCXX.h:1905
void setExpr(Expr *E)
Definition: DeclCXX.h:1930
void setKind(ExplicitSpecKind Kind)
Definition: DeclCXX.h:1929
This represents one expression.
Definition: Expr.h:110
static bool isPotentialConstantExpr(const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExpr - Return true if this function's definition might be usable in a constant exp...
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3111
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3099
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:245
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3107
bool isPRValue() const
Definition: Expr.h:278
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type.
Definition: Expr.cpp:3245
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
QualType getType() const
Definition: Expr.h:142
Represents difference between two FPOptions values.
Definition: LangOptions.h:949
Represents a member of a struct/union/class.
Definition: Decl.h:3059
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition: Decl.cpp:4576
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3220
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:4650
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition: Decl.cpp:4566
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition: Decl.h:3214
void removeInClassInitializer()
Remove the C++11 in-class initializer from this member.
Definition: Decl.h:3243
void setInClassInitializer(Expr *NewInit)
Set the C++11 in-class initializer for this member.
Definition: Decl.cpp:4586
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3272
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition: Decl.h:3283
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:72
static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc, CharSourceRange FromRange, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code from FromRange at a specific location.
Definition: Diagnostic.h:111
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:135
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:124
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:98
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition: DeclFriend.h:54
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, ArrayRef< TemplateParameterList * > FriendTypeTPLists=std::nullopt)
Definition: DeclFriend.cpp:34
void setUnsupportedFriend(bool Unsupported)
Definition: DeclFriend.h:176
static FriendTemplateDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation Loc, MutableArrayRef< TemplateParameterList * > Params, FriendUnion Friend, SourceLocation FriendLoc)
static DefaultedOrDeletedFunctionInfo * Create(ASTContext &Context, ArrayRef< DeclAccessPair > Lookups, StringLiteral *DeletedMessage=nullptr)
Definition: Decl.cpp:3100
Represents a function declaration or definition.
Definition: Decl.h:1972
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3240
ExceptionSpecificationType getExceptionSpecType() const
Gets the ExceptionSpecificationType as declared.
Definition: Decl.h:2780
bool isTrivialForCall() const
Definition: Decl.h:2344
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2440
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3717
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4058
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4046
void setIsPureVirtual(bool P=true)
Definition: Decl.cpp:3259
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2285
bool isImmediateFunction() const
Definition: Decl.cpp:3292
void setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo *Info)
Definition: Decl.cpp:3121
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3877
bool isDestroyingOperatorDelete() const
Determine whether this is a destroying operator delete.
Definition: Decl.cpp:3478
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3735
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2832
SourceLocation getDefaultLoc() const
Definition: Decl.h:2362
QualType getReturnType() const
Definition: Decl.h:2756
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition: Decl.h:2353
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2341
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4166
MutableArrayRef< ParmVarDecl * >::iterator param_iterator
Definition: Decl.h:2693
void setWillHaveBody(bool V=true)
Definition: Decl.h:2598
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3621
FunctionTypeLoc getFunctionTypeLoc() const
Find the source location information for how the type of this function was written.
Definition: Decl.cpp:3871
param_iterator param_begin()
Definition: Decl.h:2697
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3093
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition: Decl.h:2297
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2504
void setBodyContainsImmediateEscalatingExpressions(bool Set)
Definition: Decl.h:2450
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4182
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4110
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2799
bool isStatic() const
Definition: Decl.h:2840
void setTrivial(bool IT)
Definition: Decl.h:2342
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3997
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2434
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:2324
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3496
bool isImmediateEscalating() const
Definition: Decl.cpp:3272
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3310
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition: Decl.h:2827
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition: Decl.cpp:3184
void setRangeEnd(SourceLocation E)
Definition: Decl.h:2191
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2349
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition: Decl.h:2734
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4401
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2844
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2685
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3983
void setConstexprKind(ConstexprSpecKind CSK)
Definition: Decl.h:2437
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4272
void setDefaulted(bool D=true)
Definition: Decl.h:2350
bool isConsteval() const
Definition: Decl.h:2446
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition: Decl.h:2374
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
Definition: Decl.h:2773
void setBody(Stmt *B)
Definition: Decl.cpp:3252
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition: Decl.h:2315
bool hasOneParamOrDefaultArgs() const
Determine whether this function has a single parameter, or multiple parameters where all but the firs...
Definition: Decl.cpp:3749
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition: Decl.cpp:3130
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3696
size_t param_size() const
Definition: Decl.h:2701
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:2184
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3160
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition: Decl.cpp:3207
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2810
DefaultedOrDeletedFunctionInfo * getDefalutedOrDeletedInfo() const
Definition: Decl.cpp:3155
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.h:2716
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2597
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2708
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4456
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition: Type.h:4773
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4696
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:4901
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:4715
unsigned getNumParams() const
Definition: Type.h:4689
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition: Type.h:4828
ArrayRef< QualType > exceptions() const
Definition: Type.h:4858
QualType getParamType(unsigned i) const
Definition: Type.h:4691
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4700
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition: Type.h:4873
Declaration of a template function.
Definition: DeclTemplate.h:958
Wrapper for source info for functions.
Definition: TypeLoc.h:1428
unsigned getNumParams() const
Definition: TypeLoc.h:1500
void setParam(unsigned i, ParmVarDecl *VD)
Definition: TypeLoc.h:1507
ParmVarDecl * getParam(unsigned i) const
Definition: TypeLoc.h:1506
TypeLoc getReturnLoc() const
Definition: TypeLoc.h:1509
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:4282
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4056
CallingConv getCallConv() const
Definition: Type.h:4384
QualType getReturnType() const
Definition: Type.h:4373
One of these records is kept for each identifier that is lexed.
unsigned getLength() const
Efficiently return the length of this identifier info.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
ReservedLiteralSuffixIdStatus isReservedLiteralSuffixId() const
Determine whether this is a name reserved for future standardization or the implementation (C++ [usrl...
bool isPlaceholder() const
StringRef getName() const
Return the actual identifier string.
void RemoveDecl(NamedDecl *D)
RemoveDecl - Unlink the decl from its shadowed decl chain.
void AddDecl(NamedDecl *D)
AddDecl - Link the decl to its shadowed decl chain.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
IfStmt - This represents an if/then/else.
Definition: Stmt.h:2138
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition: Expr.h:1712
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3707
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2129
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:5641
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3343
ArrayRef< NamedDecl * > chain() const
Definition: Decl.h:3365
void setInherited(bool I)
Definition: Attr.h:158
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2503
ConstructorUsingShadowDecl * getShadowDecl() const
Definition: DeclCXX.h:2515
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:514
Describes an C or C++ initializer list.
Definition: Expr.h:4888
unsigned getNumInits() const
Definition: Expr.h:4918
const Expr * getInit(unsigned Init) const
Definition: Expr.h:4934
child_range children()
Definition: Expr.h:5080
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
static InitializationKind CreateDirect(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a direct initialization.
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static InitializationKind CreateDirectList(SourceLocation InitLoc)
Describes the sequence of initializations required to initialize a given object or reference with a s...
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Definition: SemaInit.cpp:8592
Describes an entity that is being initialized.
static InitializedEntity InitializeBase(ASTContext &Context, const CXXBaseSpecifier *Base, bool IsInheritedVirtualBase, const InitializedEntity *Parent=nullptr)
Create the initialization entity for a base class subobject.
Definition: SemaInit.cpp:3470
static InitializedEntity InitializeMember(FieldDecl *Member, const InitializedEntity *Parent=nullptr, bool Implicit=false)
Create the initialization entity for a member subobject.
static InitializedEntity InitializeBinding(VarDecl *Binding)
Create the initialization entity for a structured binding.
static InitializedEntity InitializeMemberFromDefaultMemberInitializer(FieldDecl *Member)
Create the initialization entity for a default member initializer.
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static InitializedEntity InitializeDelegation(QualType Type)
Create the initialization entity for a delegated constructor.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:1032
Describes the capture of a variable or of this, or of a C++1y init-capture.
Definition: LambdaCapture.h:25
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1948
bool isInitCapture(const LambdaCapture *Capture) const
Determine whether one of this lambda's captures is an init-capture.
Definition: ExprCXX.cpp:1290
capture_range captures() const
Retrieve this lambda's captures.
Definition: ExprCXX.cpp:1303
@ Ver4
Attempt to be ABI-compatible with code generated by Clang 4.0.x (SVN r291814).
@ Ver14
Attempt to be ABI-compatible with code generated by Clang 14.0.x.
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:659
void push_back(const T &LocalValue)
iterator begin(Source *source, bool LocalOnly=false)
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition: Lexer.cpp:1024
Represents a linkage specification.
Definition: DeclCXX.h:2931
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition: DeclCXX.cpp:2918
void setRBraceLoc(SourceLocation L)
Definition: DeclCXX.h:2973
bool isLocalPackExpansion(const Decl *D)
Determine whether D is a pack expansion created in this scope.
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:673
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:719
NamedDecl * next()
Definition: Lookup.h:708
bool hasNext() const
Definition: Lookup.h:704
Represents the results of name lookup.
Definition: Lookup.h:46
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:573
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition: Lookup.h:63
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition: Lookup.h:68
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Lookup.h:73
@ NotFound
No entity found met the criteria.
Definition: Lookup.h:50
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:55
@ Found
Name lookup found a single declaration that met the criteria.
Definition: Lookup.h:59
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:603
void setBaseObjectType(QualType T)
Sets the base object type for this lookup.
Definition: Lookup.h:469
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:475
DeclClass * getAsSingle() const
Definition: Lookup.h:556
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:270
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
Definition: SemaLookup.cpp:487
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:662
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:747
void setHideTags(bool Hide)
Sets whether tag declarations should be hidden by non-tag declarations during resolution.
Definition: Lookup.h:311
bool isAmbiguous() const
Definition: Lookup.h:324
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:566
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:331
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:275
NamedDecl * getAcceptableDecl(NamedDecl *D) const
Retrieve the accepted (re)declaration of the given declaration, if there is one.
Definition: Lookup.h:408
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:632
iterator end() const
Definition: Lookup.h:359
static bool isVisible(Sema &SemaRef, NamedDecl *D)
Determine whether the given declaration is visible to the program.
iterator begin() const
Definition: Lookup.h:358
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:255
An instance of this class represents the declaration of a property member.
Definition: DeclCXX.h:4232
static MSPropertyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, TypeSourceInfo *TInfo, SourceLocation StartL, IdentifierInfo *Getter, IdentifierInfo *Setter)
Definition: DeclCXX.cpp:3395
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3224
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3307
Expr * getBase() const
Definition: Expr.h:3301
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:3419
Wrapper for source info for member pointers.
Definition: TypeLoc.h:1332
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3260
Describes a module or submodule.
Definition: Module.h:105
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition: Module.h:675
bool isExplicitGlobalModule() const
Definition: Module.h:203
This represents a decl that may have a name.
Definition: Decl.h:249
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition: Decl.cpp:1082
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:463
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition: DeclBase.h:688
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:373
Represents a C++ namespace alias.
Definition: DeclCXX.h:3117
static NamespaceAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Namespace)
Definition: DeclCXX.cpp:3035
Represent a C++ namespace.
Definition: Decl.h:548
NamespaceDecl * getAnonymousNamespace() const
Retrieve the anonymous namespace nested inside this namespace, if any.
Definition: Decl.h:666
bool isInline() const
Returns true if this is an inline namespace declaration.
Definition: Decl.h:611
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition: DeclCXX.cpp:2980
void setRBraceLoc(SourceLocation L)
Definition: Decl.h:689
Class that aids in the construction of nested-name-specifiers along with source-location information ...
A C++ nested-name-specifier augmented with source location information.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, const IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
@ Global
The global specifier '::'. There is no stored value.
bool containsUnexpandedParameterPack() const
Whether this nested-name-specifier contains an unexpanded parameter pack (for C++11 variadic template...
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
const ObjCInterfaceDecl * getClassInterface() const
Definition: DeclObjC.h:2480
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2590
void setIvarInitializers(ASTContext &C, CXXCtorInitializer **initializers, unsigned numInitializers)
Definition: DeclObjC.cpp:2304
Represents an ObjC class declaration.
Definition: DeclObjC.h:1152
The basic abstraction for the target Objective-C runtime.
Definition: ObjCRuntime.h:28
bool isFragile() const
The inverse of isNonFragile(): does this runtime follow the set of implied behaviors for a "fragile" ...
Definition: ObjCRuntime.h:97
PtrTy get() const
Definition: Ownership.h:80
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1168
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:980
@ CSK_Normal
Normal lookup.
Definition: Overload.h:984
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition: Overload.h:991
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1153
MapType::iterator iterator
MapType::const_iterator const_iterator
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:254
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition: Expr.cpp:4780
Represents a parameter to a function.
Definition: Decl.h:1762
void setDefaultArg(Expr *defarg)
Definition: Decl.cpp:2984
SourceLocation getExplicitObjectParamThisLoc() const
Definition: Decl.h:1858
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition: Decl.h:1903
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1891
SourceRange getDefaultArgRange() const
Retrieve the source range that covers the entire default argument.
Definition: Decl.cpp:2989
void setUninstantiatedDefaultArg(Expr *arg)
Definition: Decl.cpp:3009
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1795
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1895
bool hasInheritedDefaultArg() const
Definition: Decl.h:1907
bool isExplicitObjectParameter() const
Definition: Decl.h:1850
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2919
Expr * getDefaultArg()
Definition: Decl.cpp:2972
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:3014
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition: Decl.cpp:3020
void setHasInheritedDefaultArg(bool I=true)
Definition: Decl.h:1911
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2942
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:126
IdentifierInfo * getPropertyDataSetter() const
Definition: ParsedAttr.h:477
IdentifierInfo * getPropertyDataGetter() const
Definition: ParsedAttr.h:471
static const ParsedAttributesView & none()
Definition: ParsedAttr.h:831
bool hasAttribute(ParsedAttr::Kind K) const
Definition: ParsedAttr.h:911
const ParsedAttr * getMSPropertyAttr() const
Definition: ParsedAttr.h:917
Wrapper for source info for pointers.
Definition: TypeLoc.h:1301
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2939
QualType getPointeeType() const
Definition: Type.h:2949
IdentifierTable & getIdentifierTable()
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6346
ArrayRef< Expr * > semantics()
Definition: Expr.h:6425
A (possibly-)qualified type.
Definition: Type.h:738
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7243
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7248
QualType withConst() const
Definition: Type.h:952
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:1018
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:949
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:805
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7199
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1230
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:7360
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7253
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition: Type.cpp:2828
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition: Type.h:890
bool isMoreQualifiedThan(QualType Other) const
Determine whether this type is more qualified than the other given type, requiring exact equality for...
Definition: Type.h:7331
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7232
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7205
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1125
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1234
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2561
The collection of all-type qualifiers we support.
Definition: Type.h:148
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:179
void removeConst()
Definition: Type.h:267
void removeAddressSpace()
Definition: Type.h:404
void addConst()
Definition: Type.h:268
void addAddressSpace(LangAS space, bool AllowDefaultAddrSpace=false)
Definition: Type.h:405
void removeVolatile()
Definition: Type.h:277
LangAS getAddressSpace() const
Definition: Type.h:379
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3242
Represents a struct/union/class.
Definition: Decl.h:4170
bool hasFlexibleArrayMember() const
Definition: Decl.h:4203
field_iterator field_end() const
Definition: Decl.h:4379
field_range fields() const
Definition: Decl.h:4376
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4361
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition: Decl.cpp:5040
specific_decl_iterator< FieldDecl > field_iterator
Definition: Decl.h:4373
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition: Decl.h:4222
bool field_empty() const
Definition: Decl.h:4384
field_iterator field_begin() const
Definition: Decl.cpp:5074
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5349
RecordDecl * getDecl() const
Definition: Type.h:5359
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:226
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:216
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:4996
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:204
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:296
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3180
QualType getPointeeType() const
Definition: Type.h:3198
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3019
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
void setEntity(DeclContext *E)
Definition: Scope.h:389
void AddDecl(Decl *D)
Definition: Scope.h:342
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:267
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:63
A generic diagnostic builder for errors which may or may not be deferred.
Definition: SemaBase.h:175
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:57
Sema & SemaRef
Definition: SemaBase.h:40
bool inferTargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose)
Given a implicit special member, infer its CUDA target from the calls it needs to make to underlying ...
Definition: SemaCUDA.cpp:447
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
static bool isTypeDecoratedWithDeclAttribute(QualType Ty)
Definition: SemaSYCL.h:362
A RAII object to enter scope of a compound statement.
Definition: Sema.h:866
std::pair< VarDecl *, Expr * > get() const
Definition: Sema.h:6048
bool isInvalid() const
Definition: Sema.h:6047
A RAII object to temporarily push a declaration context.
Definition: Sema.h:2552
For a defaulted function, the kind of defaulted function that it is.
Definition: Sema.h:4850
DefaultedComparisonKind asComparison() const
Definition: Sema.h:4882
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:4879
Expr * get() const
Definition: Sema.h:5996
Helper class that collects exception specifications for implicitly-declared special member functions.
Definition: Sema.h:4189
void CalledStmt(Stmt *S)
Integrate an invoked statement into the collected data.
void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method)
Integrate another called method into the collected data.
SpecialMemberOverloadResult - The overloading result for a special member function.
Definition: Sema.h:7497
CXXMethodDecl * getMethod() const
Definition: Sema.h:7509
RAII object to handle the state changes required to synthesize a function body.
Definition: Sema.h:10378
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:5945
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:458
void DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a function pointer.
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
CXXConstructorDecl * DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit default constructor for the given class.
bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S)
MergeCXXFunctionDecl - Merge two declarations of the same C++ function, once we already know that the...
Attr * getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition)
Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a containing class.
Definition: SemaDecl.cpp:11200
void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, SmallVectorImpl< ObjCIvarDecl * > &Ivars)
CollectIvarsToConstructOrDestruct - Collect those ivars which require initialization.
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl)
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
Definition: SemaDecl.cpp:6886
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
bool EvaluateStaticAssertMessageAsString(Expr *Message, std::string &Result, ASTContext &Ctx, bool ErrorOnInvalidMessage)
bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range)
CheckSpecifiedExceptionType - Check if the given type is valid in an exception specification.
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src)
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:9980
Decl * ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, const ParsedAttributesView &AttrList, TypeResult Type, Decl *DeclFromDeclSpec)
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
Definition: SemaDecl.cpp:9974
bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, const CXXMethodDecl *Old)
void DiagnoseAbstractType(const CXXRecordDecl *RD)
void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow)
Hides a using shadow declaration.
bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc, const LookupResult *R=nullptr, const UsingDecl *UD=nullptr)
Checks that the given nested-name qualifier used in a using decl in the current context is appropriat...
bool CheckExplicitObjectOverride(CXXMethodDecl *New, const CXXMethodDecl *Old)
llvm::SmallPtrSet< SpecialMemberDecl, 4 > SpecialMembersBeingDeclared
The C++ special members which we are currently in the process of declaring.
Definition: Sema.h:5003
void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc)
ActOnParamUnparsedDefaultArgument - We've seen a default argument for a function parameter,...
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD)
Determine the kind of defaulting that would be done for a given function.
ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs=nullptr)
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
Definition: SemaDecl.cpp:1584
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val)
Definition: SemaExpr.cpp:3916
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15819
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath)
void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old)
Merge the exception specifications of two variable declarations.
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition: Sema.h:4807
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7545
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition: Sema.h:7572
@ LookupLocalFriendName
Look up a friend of a local class.
Definition: Sema.h:7580
@ LookupNamespaceName
Look up a namespace name within a C++ using directive or namespace alias definition,...
Definition: Sema.h:7568
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:7553
void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc, ArrayRef< Expr * > Args)
DiagnoseSentinelCalls - This routine checks whether a call or message-send is to a declaration with t...
Definition: SemaExpr.cpp:491
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
Definition: SemaDecl.cpp:6822
VariadicCallType
Definition: Sema.h:2014
@ VariadicDoesNotApply
Definition: Sema.h:2019
@ VariadicConstructor
Definition: Sema.h:2018
Decl * BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc, bool Failed)
void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD)
Evaluate the implicit exception specification for a defaulted special member function.
ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E)
ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression found in an explicit(bool)...
bool DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc, RecordDecl *ClassDecl, const IdentifierInfo *Name)
void ActOnFinishCXXNonNestedClass()
MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc)
void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class)
Force the declaration of any implicitly-declared members of this class.
void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc, Expr *DefaultArg)
ActOnParamDefaultArgumentError - Parsing or semantic analysis of the default argument for the paramet...
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, TemplateIdAnnotation *TemplateId, bool IsMemberSpecialization)
Diagnose a declaration whose declarator-id has the given nested-name-specifier.
Definition: SemaDecl.cpp:6291
void DiagnoseStaticAssertDetails(const Expr *E)
Try to print more useful information about a failed static_assert with expression \E.
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared move assignment operator.
void ActOnFinishDelayedMemberInitializers(Decl *Record)
void PrintContextStack()
Definition: Sema.h:10518
void CheckDelegatingCtorCycles()
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
Definition: Sema.h:4798
void CheckExplicitObjectMemberFunction(Declarator &D, DeclarationName Name, QualType R, bool IsLambda, DeclContext *DC=nullptr)
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
Definition: SemaDecl.cpp:6258
AccessResult CheckFriendAccess(NamedDecl *D)
Checks access to the target of a friend declaration.
void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record)
MarkBaseAndMemberDestructorsReferenced - Given a record decl, mark all the non-trivial destructors of...
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition: Sema.h:826
DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D)
ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a C++ if/switch/while/for statem...
void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef< Expr * > Args, bool RequiresADL=true)
Perform lookup for an overloaded binary operator.
DelegatingCtorDeclsType DelegatingCtorDecls
All the delegating constructors seen so far in the file, used for cycle detection at the end of the T...
Definition: Sema.h:4980
bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, SourceLocation ColonLoc, const ParsedAttributesView &Attrs)
ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
std::unique_ptr< CXXFieldCollector > FieldCollector
FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
Definition: Sema.h:4961
void AddPragmaAttributes(Scope *S, Decl *D)
Adds the attributes that have been specified using the '#pragma clang attribute push' directives to t...
Definition: SemaAttr.cpp:1109
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
bool isImplicitlyDeleted(FunctionDecl *FD)
Determine whether the given function is an implicitly-deleted special member function.
void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD)
Check a completed declaration of an implicit special member.
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:17739
bool CompleteConstructorCall(CXXConstructorDecl *Constructor, QualType DeclInitType, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl< Expr * > &ConvertedArgs, bool AllowExplicit=false, bool IsListInitialization=false)
Given a constructor and the set of arguments provided for the constructor, convert the arguments and ...
@ Boolean
A boolean condition, from 'if', 'while', 'for', or 'do'.
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
Decl * ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident)
void CheckOverrideControl(NamedDecl *D)
CheckOverrideControl - Check C++11 override control semantics.
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, InheritedConstructorInfo *ICI=nullptr, bool Diagnose=false)
Determine if a special member function should have a deleted definition when it is defaulted.
@ AR_dependent
Definition: Sema.h:1076
@ AR_accessible
Definition: Sema.h:1074
@ AR_inaccessible
Definition: Sema.h:1075
@ AR_delayed
Definition: Sema.h:1077
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition: Sema.cpp:2345
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:2207
CXXConstructorDecl * DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit move constructor for the given class.
FunctionDecl * InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc, CodeSynthesisContext::SynthesisKind CSC=CodeSynthesisContext::ExplicitTemplateArgumentSubstitution)
Instantiate (or find existing instantiation of) a function template with a given set of template argu...
void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind, StringLiteral *DeletedMessage=nullptr)
void referenceDLLExportedClassMethods()
void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, CXXDestructorDecl *Dtor)
Do semantic checks to allow the complete destructor variant to be emitted when the destructor is defi...
NamedDecl * ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, Expr *BitfieldWidth, const VirtSpecifiers &VS, InClassInitStyle InitStyle)
ActOnCXXMemberDeclarator - This is invoked when a C++ class member declarator is parsed.
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckForFunctionMarkedFinal - Checks whether a virtual member function overrides a virtual member fun...
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
Definition: SemaDecl.cpp:6419
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=NoFold)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:17524
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope)
Definition: SemaDecl.cpp:4965
void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl)
AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared special functions,...
bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec)
tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
Decl * ActOnConversionDeclarator(CXXConversionDecl *Conversion)
ActOnConversionDeclarator - Called by ActOnDeclarator to complete the declaration of the given C++ co...
@ Other
C++26 [dcl.fct.def.general]p1 function-body: ctor-initializer[opt] compound-statement function-try-bl...
@ Delete
deleted-function-body
QualType BuildStdInitializerList(QualType Element, SourceLocation Loc)
Looks for the std::initializer_list template and instantiates it with Element, or emits an error if i...
MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc)
StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue=true)
Definition: SemaStmt.cpp:52
FieldDecl * HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS)
HandleField - Analyze a field of a C struct or a C++ data member.
Definition: SemaDecl.cpp:18691
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1421
void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD)
Diagnose methods which overload virtual methods in a base class without overriding any.
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
UsingShadowDecl * BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, NamedDecl *Target, UsingShadowDecl *PrevDecl)
Builds a shadow declaration corresponding to a 'using' declaration.
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallToMemberFunction - Build a call to a member function.
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, DeclAccessPair Found, QualType ObjectType, SourceLocation Loc, const PartialDiagnostic &Diag)
Is the given member accessible for the purposes of deciding whether to define a special member functi...
BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, const ParsedAttributesView &Attrs, bool Virtual, AccessSpecifier Access, ParsedType basetype, SourceLocation BaseLoc, SourceLocation EllipsisLoc)
ActOnBaseSpecifier - Parsed a base specifier.
void ActOnFinishFunctionDeclarationDeclarator(Declarator &D)
Called after parsing a function declarator belonging to a function declaration.
void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, Expr *defarg)
ActOnParamDefaultArgument - Check whether the default argument provided for a function parameter is w...
void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC)
CheckConversionDeclarator - Called by ActOnDeclarator to check the well-formednes of the conversion f...
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition: Sema.h:859
void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnFinishDelayedCXXMethodDeclaration - We have finished processing the delayed method declaration f...
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
Definition: SemaDecl.cpp:5957
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
Decl * ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceLocation IdentLoc, IdentifierInfo &II, CXXScopeSpec *SS=nullptr)
void propagateDLLAttrToBaseClassTemplate(CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc)
Perform propagation of DLL attributes from a derived class to a templated base class for MS compatibi...
NamedDecl * ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams)
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
Definition: SemaDecl.cpp:5075
void CheckDelayedMemberExceptionSpecs()
void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param)
This is used to implement the constant expression evaluation part of the attribute enable_if extensio...
AllowFoldKind
Definition: Sema.h:5959
@ AllowFold
Definition: Sema.h:5961
@ NoFold
Definition: Sema.h:5960
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1522
ClassTemplateDecl * StdInitializerList
The C++ "std::initializer_list" template, which is defined in <initializer_list>.
Definition: Sema.h:4987
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD)
bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS=nullptr)
isCurrentClassName - Determine whether the identifier II is the name of the class type currently bein...
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var)
Mark a variable referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
Definition: SemaExpr.cpp:20220
void checkExceptionSpecification(bool IsTopLevel, ExceptionSpecificationType EST, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr, SmallVectorImpl< QualType > &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI)
Check the given exception-specification and update the exception specification information with the r...
SmallVector< std::pair< FunctionDecl *, FunctionDecl * >, 2 > DelayedEquivalentExceptionSpecChecks
All the function redeclarations seen during a class definition that had their exception spec checks d...
Definition: Sema.h:5065
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method)
Check whether 'this' shows up in the type of a static member function after the (naturally empty) cv-...
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:18165
NamespaceDecl * getOrCreateStdNamespace()
Retrieve the special "std" namespace, which may require us to implicitly define the namespace.
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:672
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init....
void ActOnStartFunctionDeclarationDeclarator(Declarator &D, unsigned TemplateParameterDepth)
Called before parsing a function declarator belonging to a function declaration.
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths)
Builds a string representing ambiguous paths from a specific derived class to different subobjects of...
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition: Sema.h:4652
@ Relational
This is an <, <=, >, or >= that should be implemented as a rewrite in terms of a <=> comparison.
@ NotEqual
This is an operator!= that should be implemented as a rewrite in terms of a == comparison.
@ ThreeWay
This is an operator<=> that should be implemented as a series of subobject comparisons.
@ None
This is not a defaultable comparison operator.
@ Equal
This is an operator== that should be implemented as a series of subobject comparisons.
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
Definition: SemaType.cpp:9754
llvm::PointerIntPair< CXXRecordDecl *, 3, CXXSpecialMemberKind > SpecialMemberDecl
Definition: Sema.h:4998
void ActOnStartCXXInClassMemberInitializer()
Enter a new C++ default initializer scope.
NamedDecl * BuildUsingDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList, bool IsInstantiation, bool IsUsingIfExists)
Builds a using declaration.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:776
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2274
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef< CXXCtorInitializer * > Initializers=std::nullopt)
void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitMoveConstructor - Checks for feasibility of defining this constructor as the move const...
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition: Sema.h:9460
EnumDecl * getStdAlignValT() const
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record)
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition: Sema.cpp:1560
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:6645
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
Definition: SemaType.cpp:1979
void PushFunctionScope()
Enter a new function scope.
Definition: Sema.cpp:2226
void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc)
void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitCopyConstructor - Checks for feasibility of defining this constructor as the copy const...
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
Definition: SemaExpr.cpp:20736
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:63
@ UPPC_RequiresClause
Definition: Sema.h:11053
@ UPPC_UsingDeclaration
A using declaration.
Definition: Sema.h:11008
@ UPPC_ExceptionType
The type of an exception.
Definition: Sema.h:11026
@ UPPC_Initializer
An initializer.
Definition: Sema.h:11017
@ UPPC_BaseType
The base type of a class type.
Definition: Sema.h:10987
@ UPPC_FriendDeclaration
A friend declaration.
Definition: Sema.h:11011
@ UPPC_DefaultArgument
A default argument.
Definition: Sema.h:11020
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition: Sema.h:10990
@ UPPC_DataMemberType
The type of a data member.
Definition: Sema.h:10993
@ UPPC_StaticAssertExpression
The expression in a static assertion.
Definition: Sema.h:10999
Decl * ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, SourceLocation NamespaceLoc, SourceLocation IdentLoc, IdentifierInfo *Ident, SourceLocation LBrace, const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UsingDecl, bool IsNested)
ActOnStartNamespaceDef - This is called at the start of a namespace definition.
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc, ComparisonCategoryUsage Usage)
Lookup the specified comparison category types in the standard library, an check the VarDecls possibl...
bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList)
void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent)
DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was not used in the declaration of ...
SmallVector< VTableUse, 16 > VTableUses
The list of vtables that are required but have not yet been materialized.
Definition: Sema.h:4542
AccessResult CheckStructuredBindingMemberAccess(SourceLocation UseLoc, CXXRecordDecl *DecomposedClass, DeclAccessPair Field)
Checks implicit access to a member in a structured binding.
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
Definition: SemaDecl.cpp:1412
void ActOnBaseSpecifiers(Decl *ClassDecl, MutableArrayRef< CXXBaseSpecifier * > Bases)
ActOnBaseSpecifiers - Attach the given base specifiers to the class, after checking whether there are...
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, const ProcessDeclAttributeOptions &Options=ProcessDeclAttributeOptions())
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK)
bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B)
Determine if A and B are equivalent internal linkage declarations from different modules,...
Preprocessor & PP
Definition: Sema.h:858
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind)
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:6717
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck=false, bool ForceUnprivileged=false)
Checks access for a hierarchy conversion.
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
NamedDecl * getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R)
Return the declaration shadowed by the given typedef D, or null if it doesn't shadow any declaration ...
Definition: SemaDecl.cpp:8443
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddBuiltinOperatorCandidates - Add the appropriate built-in operator overloads to the candidate set (...
ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind)
ActOnCXXBoolLiteral - Parse {true,false} literals.
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD)
void checkClassLevelDLLAttribute(CXXRecordDecl *Class)
Check class-level dllimport/dllexport attribute.
bool CheckConstraintSatisfaction(const NamedDecl *Template, ArrayRef< const Expr * > ConstraintExprs, const MultiLevelTemplateArgumentList &TemplateArgLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction)
Check whether the given list of constraint expressions are satisfied (as if in a 'conjunction') given...
Definition: Sema.h:11439
const LangOptions & LangOpts
Definition: Sema.h:857
void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation)
SetIvarInitializers - This routine builds initialization ASTs for the Objective-C implementation whos...
std::pair< Expr *, std::string > findFailedBooleanCondition(Expr *Cond)
Find the failed Boolean condition within a given Boolean constant expression, and describe it with a ...
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock)
void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, bool ConstexprOnly=false)
MarkVirtualMembersReferenced - Will mark all members of the given CXXRecordDecl referenced.
const LangOptions & getLangOpts() const
Definition: Sema.h:521
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
Definition: SemaExpr.cpp:17861
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
Definition: SemaInit.cpp:8555
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition: Sema.h:4965
void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor)
Define the specified inheriting constructor.
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization, bool DeclIsDefn)
Perform semantic checking of a new function declaration.
Definition: SemaDecl.cpp:12145
CXXRecordDecl * getStdBadAlloc() const
QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckDestructorDeclarator - Called by ActOnDeclarator to check the well-formednes of the destructor d...
bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange)
Mark the given method pure.
void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
void NoteHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl< CXXMethodDecl * > &OverloadedMethods)
CXXMethodDecl * DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit move assignment operator for the given class.
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
llvm::DenseMap< CXXRecordDecl *, bool > VTablesUsed
The set of classes whose vtables have been used within this translation unit, and a bit that will be ...
Definition: Sema.h:4548
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
ComparisonCategoryUsage
Definition: Sema.h:4042
@ DefaultedOperator
A defaulted 'operator<=>' needed the comparison category.
SmallVector< InventedTemplateParameterInfo, 4 > InventedParameterInfos
Stack containing information needed when in C++2a an 'auto' is encountered in a function declaration ...
Definition: Sema.h:4958
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:20377
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
NamedDecl * BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceLocation NameLoc, TypeSourceInfo *EnumType, EnumDecl *ED)
TypeLoc getReturnTypeLoc(FunctionDecl *FD) const
Definition: SemaStmt.cpp:3856
SmallVector< std::pair< const CXXMethodDecl *, const CXXMethodDecl * >, 2 > DelayedOverridingExceptionSpecChecks
All the overriding functions seen during a class definition that had their exception spec checks dela...
Definition: Sema.h:5057
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition: Sema.h:4991
void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, const CXXRecordDecl *RD)
Mark the exception specifications of all virtual member functions in the given class as needed.
ExprResult BuildConvertedConstantExpression(Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest=nullptr)
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl=nullptr)
Retrieve a version of the type 'T' that is elaborated by Keyword, qualified by the nested-name-specif...
Definition: SemaType.cpp:9853
bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L, CXXScopeSpec *SS=nullptr)
Require that the EnumDecl is completed with its enumerators defined or instantiated.
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool UseMemberUsingDeclRules)
Determine whether the given New declaration is an overload of the declarations in Old.
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl)
CheckOverloadedOperatorDeclaration - Check whether the declaration of this overloaded operator is wel...
void ExitDeclaratorContext(Scope *S)
Definition: SemaDecl.cpp:1399
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir)
void CheckConstructor(CXXConstructorDecl *Constructor)
CheckConstructor - Checks a fully-formed constructor for well-formedness, issuing any diagnostics req...
void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a block pointer.
void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor)
DefineImplicitDestructor - Checks for feasibility of defining this destructor as the default destruct...
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMemberKind CSM)
Diagnose why the specified class does not have a trivial special member of the given kind.
CXXRecordDecl * getCurrentClass(Scope *S, const CXXScopeSpec *SS)
Get the class that is directly named by the current context.
void pushCodeSynthesisContext(CodeSynthesisContext Ctx)
QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity)
Build a reference type.
Definition: SemaType.cpp:2282
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr)
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method)
Check whether 'this' shows up in the attributes of the given static member function.
CXXBaseSpecifier * CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
ActOnBaseSpecifier - Parsed a base specifier.
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody=nullptr)
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations
A mapping from parameters with unparsed default arguments to the set of instantiations of each parame...
Definition: Sema.h:9992
void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitDefaultConstructor - Checks for feasibility of defining this constructor as the default...
std::pair< CXXRecordDecl *, SourceLocation > VTableUse
The list of classes whose vtables have been used within this translation unit, and the source locatio...
Definition: Sema.h:4538
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:719
bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow)
Determines whether to create a using shadow decl for a particular decl, given the set of decls existi...
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3500
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:11925
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC)
Check the validity of a declarator that we parsed for a deduction-guide.
void DiagPlaceholderVariableDefinition(SourceLocation Loc)
void CheckForFunctionRedefinition(FunctionDecl *FD, const FunctionDecl *EffectiveDefinition=nullptr, SkipBodyInfo *SkipBody=nullptr)
Definition: SemaDecl.cpp:15703
bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc)
Definition: Sema.h:5380
std::unique_ptr< RecordDeclSetTy > PureVirtualClassDiagSet
PureVirtualClassDiagSet - a set of class declarations which we have emitted a list of pure virtual fu...
Definition: Sema.h:4972
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
Definition: SemaDecl.cpp:15630
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:997
bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl *&Operator, bool Diagnose=true, bool WantSize=false, bool WantAligned=false)
VarDecl * BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id)
Perform semantic analysis for the variable declaration that occurs within a C++ catch clause,...
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
Definition: SemaDecl.cpp:15173
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5963
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition: Sema.h:7908
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared copy assignment operator.
SemaSYCL & SYCL()
Definition: Sema.h:1019
bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, CXXCtorInitializer *Initializer)
TrivialABIHandling
Definition: Sema.h:4837
@ TAH_IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition: Sema.h:4839
@ TAH_ConsiderTrivialABI
The triviality of a method affected by "trivial_abi".
Definition: Sema.h:4842
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:6456
bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl)
CheckLiteralOperatorDeclaration - Check whether the declaration of this literal operator function is ...
bool DefineUsedVTables()
Define all of the vtables that have been used in this translation unit and reference any virtual memb...
CXXMethodDecl * DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit copy assignment operator for the given class.
void MarkVirtualBaseDestructorsReferenced(SourceLocation Location, CXXRecordDecl *ClassDecl, llvm::SmallPtrSetImpl< const RecordType * > *DirectVirtualBases=nullptr)
Mark destructors of virtual bases of this class referenced.
void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD)
Check that the C++ class annoated with "trivial_abi" satisfies all the conditions that are needed for...
SourceManager & getSourceManager() const
Definition: Sema.h:526
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:20324
StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body)
Definition: SemaStmt.cpp:2165
unsigned ActOnReenterTemplateScope(Decl *Template, llvm::function_ref< Scope *()> EnterScope)
ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, CXXConstructionKind ConstructKind, SourceRange ParenRange)
BuildCXXConstructExpr - Creates a complete call to a constructor, including handling of its default a...
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:10677
@ AA_Passing
Definition: Sema.h:5367
FunctionDecl * SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, FunctionDecl *Spaceship)
Substitute the name and return type of a defaulted 'operator<=>' to form an implicit 'operator=='.
NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists)
Decl * ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams)
Handle a friend type declaration.
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
void EnterDeclaratorContext(Scope *S, DeclContext *DC)
EnterDeclaratorContext - Used when we must lookup names in the context of a declarator's nested name ...
Definition: SemaDecl.cpp:1364
bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD, DefaultedComparisonKind DCK)
bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method)
Whether this' shows up in the exception specification of a static member function.
llvm::FoldingSet< SpecialMemberOverloadResultEntry > SpecialMemberCache
A cache of special member function overload resolution results for C++ records.
Definition: Sema.h:7525
QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, SourceLocation EllipsisLoc, bool FullySubstituted=false, ArrayRef< QualType > Expansions={})
Definition: SemaType.cpp:10000
Decl * ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, Expr *LangStr, SourceLocation LBraceLoc)
ActOnStartLinkageSpecification - Parsed the beginning of a C++ linkage specification,...
void FilterUsingLookup(Scope *S, LookupResult &lookup)
Remove decls we can't actually see from a lookup being used to declare shadow using decls.
void actOnDelayedExceptionSpecification(Decl *Method, ExceptionSpecificationType EST, SourceRange SpecificationRange, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr)
Add an exception-specification to the given member function (or member function template).
Decl * ActOnExceptionDeclarator(Scope *S, Declarator &D)
ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch handler.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, Expr *Init)
This is invoked after parsing an in-class initializer for a non-static C++ class member,...
QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, SourceLocation Loc)
PushNamespaceVisibilityAttr - Note that we've entered a namespace with a visibility attribute.
Definition: SemaAttr.cpp:1380
void ActOnDefaultCtorInitializers(Decl *CDtorDecl)
void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, ArrayRef< CXXCtorInitializer * > MemInits, bool AnyErrors)
ActOnMemInitializers - Handle the member initializers for a constructor.
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an initializer for the declaration ...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:227
void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
SemaHLSL & HLSL()
Definition: Sema.h:1004
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
Definition: SemaDecl.cpp:8477
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor)
Build an exception spec for destructors that don't have one.
Decl * ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc)
StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, bool AllowRecovery=false)
Definition: SemaStmt.cpp:4019
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:11900
bool CheckImmediateEscalatingFunctionDefinition(FunctionDecl *FD, const sema::FunctionScopeInfo *FSI)
void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor)
In the MS ABI, we need to instantiate default arguments of dllexported default constructors along wit...
@ CTK_ErrorRecovery
Definition: Sema.h:7774
void CheckCompleteVariableDeclaration(VarDecl *VD)
Definition: SemaDecl.cpp:14530
ExprResult ActOnRequiresClause(ExprResult ConstraintExpr)
void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class)
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL,...
RedeclarationKind forRedeclarationInCurContext() const
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition: Sema.h:4983
bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, bool HasTypenameKeyword, const CXXScopeSpec &SS, SourceLocation NameLoc, const LookupResult &Previous)
Checks that the given using declaration is not an invalid redeclaration.
@ CCEK_StaticAssertMessageSize
Call to size() in a static assert message.
Definition: Sema.h:8202
@ CCEK_ExplicitBool
Condition in an explicit(bool) specifier.
Definition: Sema.h:8200
@ CCEK_StaticAssertMessageData
Call to data() in a static assert message.
Definition: Sema.h:8204
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3253
ASTContext & getASTContext() const
Definition: Sema.h:528
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type.
Definition: SemaDecl.cpp:291
ASTConsumer & Consumer
Definition: Sema.h:860
void ActOnFinishCXXMemberDecls()
Perform any semantic analysis which needs to be delayed until all pending class member declarations h...
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:3432
@ Ovl_NonFunction
This is not an overload because the lookup results contain a non-function.
Definition: Sema.h:8103
@ Ovl_Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition: Sema.h:8095
@ Ovl_Match
This is not an overload because the signature exactly matches an existing declaration.
Definition: Sema.h:8099
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:120
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:5417
Decl * ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec, SourceLocation RBraceLoc)
ActOnFinishLinkageSpecification - Complete the definition of the C++ linkage specification LinkageSpe...
bool CheckInheritingConstructorUsingDecl(UsingDecl *UD)
Additional checks for a using declaration referring to a constructor name.
bool inferObjCARCLifetime(ValueDecl *decl)
Definition: SemaDecl.cpp:7040
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
QualType BuildDecltypeType(Expr *E, bool AsUnevaluated=true)
If AsUnevaluated is false, E is treated as though it were an evaluated context, such as when building...
Definition: SemaType.cpp:9968
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:6148
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, OffsetOfKind OOK, SkipBodyInfo *SkipBody=nullptr)
This is invoked when we see 'struct foo' or 'struct {'.
Definition: SemaDecl.cpp:17426
void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace)
ActOnFinishNamespaceDef - This callback is called after a namespace is exited.
MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *Init, SourceLocation EllipsisLoc)
Handle a C++ member initializer.
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9368
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:831
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:19425
void CheckExplicitObjectLambda(Declarator &D)
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD)
void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc)
PopPragmaVisibility - Pop the top element of the visibility stack; used for '#pragma GCC visibility' ...
Definition: SemaAttr.cpp:1389
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init)
Check that the lifetime of the initializer (and its subobjects) is sufficient for initializing the en...
Definition: SemaInit.cpp:8137
FPOptions & getCurFPFeatures()
Definition: Sema.h:523
void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record)
Perform semantic checks on a class definition that has been completing, introducing implicitly-declar...
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:18243
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1329
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition: Sema.h:862
bool CheckDestructor(CXXDestructorDecl *Destructor)
CheckDestructor - Checks a fully-formed destructor definition for well-formedness,...
NamedDecl * BuildUsingPackDecl(NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl * > Expansions)
MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, SourceLocation LParenLoc, ArrayRef< Expr * > Args, SourceLocation RParenLoc, SourceLocation EllipsisLoc)
Handle a C++ member initializer using parentheses syntax.
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc, StringLiteral *Message=nullptr)
void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnStartDelayedCXXMethodDeclaration - We have completed parsing a top-level (non-nested) C++ class,...
DiagnosticsEngine & Diags
Definition: Sema.h:861
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg)
Definition: Sema.h:6017
CXXConstructorDecl * DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit copy constructor for the given class.
NamespaceDecl * getStdNamespace() const
void DeclareImplicitEqualityComparison(CXXRecordDecl *RD, FunctionDecl *Spaceship)
bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef< CXXBaseSpecifier * > Bases)
Performs the actual work of attaching the given base class specifiers to a C++ class.
void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an initializer for the declaratio...
@ TUK_Friend
Definition: Sema.h:3193
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
Definition: SemaDecl.cpp:7457
@ TPC_TypeAliasTemplate
Definition: Sema.h:9204
SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMemberKind SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis)
NamedDecl * ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration)
ActOnTypedefNameDecl - Perform semantic checking for a declaration which declares a typedef-name,...
Definition: SemaDecl.cpp:6926
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Definition: SemaExpr.cpp:5849
Decl * ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc)
Handle a C++11 empty-declaration and attribute-declaration.
void PopDeclContext()
Definition: SemaDecl.cpp:1336
void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc=SourceLocation(), SourceLocation VolatileQualLoc=SourceLocation(), SourceLocation RestrictQualLoc=SourceLocation(), SourceLocation AtomicQualLoc=SourceLocation(), SourceLocation UnalignedQualLoc=SourceLocation())
Definition: SemaType.cpp:3357
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:4995
QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckConstructorDeclarator - Called by ActOnDeclarator to check the well-formedness of the constructo...
ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
Definition: SemaDecl.cpp:1606
FunctionDecl * FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD)
SemaOpenMP & OpenMP()
Definition: Sema.h:1014
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:9336
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
Definition: SemaDecl.cpp:1589
@ OOK_Outside
Definition: Sema.h:3198
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:13601
bool isUsualDeallocationFunction(const CXXMethodDecl *FD)
void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD)
Produce notes explaining why a defaulted function was defined as deleted.
ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *Ty, Expr *E, SourceRange AngleBrackets, SourceRange Parens)
Definition: SemaCast.cpp:299
bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionExceptionSpec - Checks whether the exception spec is a subset of base spec.
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition: Sema.h:4797
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
Definition: SemaExpr.cpp:18426
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionReturnType - Checks whether the return types are covariant,...
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef< Expr * > Args, SmallVectorImpl< Expr * > &AllArgs, VariadicCallType CallType=VariadicDoesNotApply, bool AllowExplicit=false, bool IsListInitialization=false)
GatherArgumentsForCall - Collector argument expressions for various form of call prototypes.
Definition: SemaExpr.cpp:6199
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:21524
Decl * ActOnDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:6225
AbstractDiagSelID
Definition: Sema.h:4752
@ AbstractVariableType
Definition: Sema.h:4756
@ AbstractReturnType
Definition: Sema.h:4754
@ AbstractNone
Definition: Sema.h:4753
@ AbstractFieldType
Definition: Sema.h:4757
@ AbstractArrayType
Definition: Sema.h:4760
@ AbstractParamType
Definition: Sema.h:4755
StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal)
Definition: SemaStmt.cpp:909
MSPropertyDecl * HandleMSProperty(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS, const ParsedAttr &MSPropertyAttr)
HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
Definition: SemaDecl.cpp:1729
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition: Sema.h:6649
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
Definition: SemaExpr.cpp:15131
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc)
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
CheckConstexprKind
Definition: Sema.h:4903
@ CheckValid
Identify whether this function satisfies the formal rules for constexpr functions in the current lanu...
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
void LoadExternalVTableUses()
Load any externally-stored vtable uses.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:3237
Decl * ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, SourceLocation NamespcLoc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *NamespcName, const ParsedAttributesView &AttrList)
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:525
StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef< Stmt * > Elts, bool isStmtExpr)
Definition: SemaStmt.cpp:415
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D)
void FindHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl< CXXMethodDecl * > &OverloadedMethods)
Check if a method overloads virtual methods in a base class without overriding any.
IdentifierResolver IdResolver
Definition: Sema.h:2545
DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists)
Handle a friend tag declaration where the scope specifier was templated.
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record)
bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, TrivialABIHandling TAH=TAH_IgnoreTrivialABI, bool Diagnose=false)
Determine whether a defaulted or deleted special member function is trivial, as specified in C++11 [c...
ExprResult ActOnCXXThis(SourceLocation Loc)
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef< UnexpandedParameterPack > Unexpanded)
Diagnose unexpanded parameter packs.
CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow)
Given a derived-class using shadow declaration for a constructor and the correspnding base class cons...
void warnOnReservedIdentifier(const NamedDecl *D)
Definition: SemaDecl.cpp:6212
bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, SourceLocation DefaultLoc)
bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS)
Determine whether the identifier II is a typo for the name of the class type currently being defined.
SemaCUDA & CUDA()
Definition: Sema.h:999
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings=std::nullopt)
Definition: SemaDecl.cpp:7625
Decl * ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation TypenameLoc, CXXScopeSpec &SS, UnqualifiedId &Name, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList)
void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param)
ActOnDelayedCXXMethodParameter - We've already started a delayed C++ method declaration.
bool isAbstractType(SourceLocation Loc, QualType T)
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr, bool SkipImmediateInvocations=true)
Instantiate or parse a C++ default argument expression as necessary.
Definition: SemaExpr.cpp:5645
ValueDecl * tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl, const IdentifierInfo *MemberOrBase)
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:577
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, bool RecoverUncorrectedTypos=false, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
void DiagnoseImmediateEscalatingReason(FunctionDecl *FD)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:6902
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
CXXDestructorDecl * DeclareImplicitDestructor(CXXRecordDecl *ClassDecl)
Declare the implicit destructor for the given class.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
A trivial tuple used to represent a source range.
void setBegin(SourceLocation b)
bool isInvalid() const
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
void setEnd(SourceLocation e)
static StaticAssertDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *Message, SourceLocation RParenLoc, bool Failed)
Definition: DeclCXX.cpp:3303
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
child_range children()
Definition: Stmt.cpp:287
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
static bool isValidUDSuffix(const LangOptions &LangOpts, StringRef Suffix)
Determine whether a suffix is a valid ud-suffix.
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1773
bool isUnevaluated() const
Definition: Expr.h:1902
StringRef getString() const
Definition: Expr.h:1850
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3586
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3709
StringRef getKindName() const
Definition: Decl.h:3777
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3689
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:4732
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4726
bool isUnion() const
Definition: Decl.h:3792
TagKind getTagKind() const
Definition: Decl.h:3781
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition: Decl.h:3740
bool areArgsDestroyedLeftToRightInCallee() const
Are arguments to a call destroyed left to right in the callee? This is a fundamental language change,...
Definition: TargetCXXABI.h:188
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
bool hasKeyFunctions() const
Does this ABI use key functions? If so, class data such as the vtable is emitted with strong linkage ...
Definition: TargetCXXABI.h:206
virtual CallingConvKind getCallingConvKind(bool ClangABICompat4) const
Definition: TargetInfo.cpp:617
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1235
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1306
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
Definition: TargetInfo.h:1273
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:667
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:659
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
TypeSourceInfo * getTypeSourceInfo() const
Definition: TemplateBase.h:578
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:574
Represents a template argument.
Definition: TemplateBase.h:61
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:202
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
NameKind getKind() const
@ UsingTemplate
A template name that refers to a template declaration found through a specific using shadow declarati...
Definition: TemplateName.h:247
@ Template
A single template declaration.
Definition: TemplateName.h:219
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:203
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to form a template specialization.
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:201
SourceLocation getLAngleLoc() const
Definition: DeclTemplate.h:200
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:144
static bool shouldIncludeTypeForArgument(const PrintingPolicy &Policy, const TemplateParameterList *TPL, unsigned Idx)
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:180
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:199
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition: TypeLoc.h:1695
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:5889
Declaration of a template type parameter.
unsigned getIndex() const
Retrieve the index of the template parameter.
unsigned getDepth() const
Retrieve the depth of the template parameter.
unsigned getIndex() const
Definition: Type.h:5579
unsigned getDepth() const
Definition: Type.h:5578
The top declaration context.
Definition: Decl.h:84
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition: Decl.h:3557
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5559
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT)
Definition: Decl.h:3576
Declaration of an alias template.
TypeAliasDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
static TypeAliasTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
Represents a declaration of a type.
Definition: Decl.h:3392
const Type * getTypeForDecl() const
Definition: Decl.h:3416
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition: TypeLoc.h:133
TypeLoc getNextTypeLoc() const
Get the next TypeLoc pointed by this TypeLoc, e.g for "int*" the TypeLoc is a PointerLoc and next Typ...
Definition: TypeLoc.h:170
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:89
TypeLoc IgnoreParens() const
Definition: TypeLoc.h:1225
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition: TypeLoc.h:78
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:153
SourceRange getLocalSourceRange() const
Get the local source range.
Definition: TypeLoc.h:159
TypeLocClass getTypeLocClass() const
Definition: TypeLoc.h:116
bool isNull() const
Definition: TypeLoc.h:121
SourceLocation getEndLoc() const
Get the end source location.
Definition: TypeLoc.cpp:235
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2684
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7130
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7141
A reasonable base class for TypeLocs that correspond to types that are written as a type-specifier.
Definition: TypeLoc.h:528
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition: Type.cpp:3139
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition: Type.h:6152
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:3121
The base class of the type hierarchy.
Definition: Type.h:1607
bool isSizelessType() const
As an extension, we classify types as one of "sized" or "sizeless"; every type is one or the other.
Definition: Type.cpp:2454
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1870
bool isVoidType() const
Definition: Type.h:7723
bool isBooleanType() const
Definition: Type.h:7851
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2880
bool isIncompleteArrayType() const
Definition: Type.h:7486
bool isUndeducedAutoType() const
Definition: Type.h:7561
bool isRValueReferenceType() const
Definition: Type.h:7432
bool isArrayType() const
Definition: Type.h:7478
bool isPointerType() const
Definition: Type.h:7412
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7763
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8008
bool isReferenceType() const
Definition: Type.h:7424
bool isEnumeralType() const
Definition: Type.h:7510
bool isElaboratedTypeSpecifier() const
Determine wither this type is a C++ elaborated-type-specifier.
Definition: Type.cpp:3246
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:694
bool isLValueReferenceType() const
Definition: Type.h:7428
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:7692
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2449
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2114
QualType getCanonicalTypeInternal() const
Definition: Type.h:2732
bool containsErrors() const
Whether this type is an error type.
Definition: Type.h:2443
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:7891
bool isFunctionProtoType() const
Definition: Type.h:2284
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition: Type.h:7864
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2467
bool isObjCObjectType() const
Definition: Type.h:7548
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:7857
bool isFunctionType() const
Definition: Type.h:7408
bool isObjCObjectPointerType() const
Definition: Type.h:7544
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2254
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7941
bool isRecordType() const
Definition: Type.h:7506
bool isUnionType() const
Definition: Type.cpp:660
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition: Type.cpp:1878
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1874
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3434
QualType getUnderlyingType() const
Definition: Decl.h:3489
Simple class containing the result of Sema::CorrectTypo.
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
DeclClass * getCorrectionDeclAs() const
SourceRange getCorrectionRange() const
void WillReplaceSpecifier(bool ForceReplacement)
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2235
Opcode getOpcode() const
Definition: Expr.h:2275
Expr * getSubExpr() const
Definition: Expr.h:2280
static bool isIncrementDecrementOp(Opcode Op)
Definition: Expr.h:2335
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4895
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1024
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition: DeclSpec.h:1060
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:1236
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition: DeclSpec.h:1233
UnionParsedType DestructorName
When Kind == IK_DestructorName, the type referred to by the class-name.
Definition: DeclSpec.h:1068
UnionParsedTemplateTy TemplateName
When Kind == IK_DeductionGuideName, the parsed template-name.
Definition: DeclSpec.h:1071
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1106
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:1076
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent)
Definition: ExprCXX.cpp:372
A set of unresolved declarations.
Definition: UnresolvedSet.h:61
ArrayRef< DeclAccessPair > pairs() const
Definition: UnresolvedSet.h:89
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
A set of unresolved declarations.
This node is generated when a using-declaration that was annotated with attribute((using_if_exists)) ...
Definition: DeclCXX.h:4037
static UnresolvedUsingIfExistsDecl * Create(ASTContext &Ctx, DeclContext *DC, SourceLocation Loc, DeclarationName Name)
Definition: DeclCXX.cpp:3283
Represents a dependent using declaration which was marked with typename.
Definition: DeclCXX.h:3956
static UnresolvedUsingTypenameDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TargetNameLoc, DeclarationName TargetName, SourceLocation EllipsisLoc)
Definition: DeclCXX.cpp:3263
Represents a dependent using declaration which was not marked with typename.
Definition: DeclCXX.h:3859
static UnresolvedUsingValueDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, SourceLocation EllipsisLoc)
Definition: DeclCXX.cpp:3235
Represents a C++ using-declaration.
Definition: DeclCXX.h:3509
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name.
Definition: DeclCXX.h:3546
bool hasTypename() const
Return true if the using declaration has 'typename'.
Definition: DeclCXX.h:3558
DeclarationNameInfo getNameInfo() const
Definition: DeclCXX.h:3550
static UsingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
Definition: DeclCXX.cpp:3170
SourceLocation getUsingLoc() const
Return the source location of the 'using' keyword.
Definition: DeclCXX.h:3536
Represents C++ using-directive.
Definition: DeclCXX.h:3012
static UsingDirectiveDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation NamespaceLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Nominated, DeclContext *CommonAncestor)
Definition: DeclCXX.cpp:2935
Represents a C++ using-enum-declaration.
Definition: DeclCXX.h:3710
static UsingEnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, SourceLocation EnumL, SourceLocation NameL, TypeSourceInfo *EnumType)
Definition: DeclCXX.cpp:3191
static UsingPackDecl * Create(ASTContext &C, DeclContext *DC, NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl * > UsingDecls)
Definition: DeclCXX.cpp:3213
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3317
static UsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, DeclarationName Name, BaseUsingDecl *Introducer, NamedDecl *Target)
Definition: DeclCXX.h:3353
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3381
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition: DeclCXX.cpp:3110
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:707
void setType(QualType newType)
Definition: Decl.h:719
QualType getType() const
Definition: Decl.h:718
QualType getType() const
Definition: Value.cpp:234
Represents a variable declaration or definition.
Definition: Decl.h:919
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2791
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2152
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1550
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition: Decl.cpp:2261
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2191
bool isNoDestroy(const ASTContext &) const
Is destruction of this variable entirely suppressed? If so, the variable need not have a usable destr...
Definition: Decl.cpp:2817
void setCXXCondDecl()
Definition: Decl.h:1600
bool isInlineSpecified() const
Definition: Decl.h:1535
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2555
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1271
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1214
bool evaluateDestruction(SmallVectorImpl< PartialDiagnosticAt > &Notes) const
Evaluate the destruction of this variable to determine if it constitutes constant destruction.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1196
const Expr * getInit() const
Definition: Decl.h:1356
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition: Decl.cpp:2824
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1165
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition: Decl.h:945
void setInit(Expr *I)
Definition: Decl.cpp:2458
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1156
bool isUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value can be used in a constant expression, according to the releva...
Definition: Decl.cpp:2509
void setExceptionVariable(bool EV)
Definition: Decl.h:1478
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2667
Declaration of a variable template.
Represents a GCC generic vector type.
Definition: Type.h:3769
unsigned getNumElements() const
Definition: Type.h:3784
QualType getElementType() const
Definition: Type.h:3783
Represents a C++11 virt-specifier-seq.
Definition: DeclSpec.h:2778
SourceLocation getOverrideLoc() const
Definition: DeclSpec.h:2798
SourceLocation getLastLocation() const
Definition: DeclSpec.h:2810
bool isOverrideSpecified() const
Definition: DeclSpec.h:2797
SourceLocation getFinalLoc() const
Definition: DeclSpec.h:2802
bool isFinalSpecified() const
Definition: DeclSpec.h:2800
bool isFinalSpelledSealed() const
Definition: DeclSpec.h:2801
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:104
bool FoundImmediateEscalatingExpression
Whether we found an immediate-escalating expression.
Definition: ScopeInfo.h:179
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition: limits.h:60
const AstTypeMatcher< RecordType > recordType
Matches record types (e.g.
static Base getBase(const StringRef IntegerLiteral)
@ After
Like System, but searched after the system directories.
@ FixIt
Parse and apply any fixits to the source.
llvm::APInt APInt
Definition: Integral.h:29
static T getParam(const InterpFrame *Frame, unsigned Index)
bool This(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1893
bool Inc(InterpState &S, CodePtr OpPC)
1) Pops a pointer from the stack 2) Load the value from the pointer 3) Writes the value increased by ...
Definition: Interp.h:589
bool LE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:882
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1867
bool Init(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1461
bool Comp(InterpState &S, CodePtr OpPC)
1) Pops the value from the stack.
Definition: Interp.h:708
std::string toString(const til::SExpr *E)
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition: FixIt.h:32
Stencil access(llvm::StringRef BaseId, Stencil Member)
Constructs a MemberExpr that accesses the named member (Member) of the object bound to BaseId.
The JSON file list parser is used to communicate input to InstallAPI.
@ If
'if' clause, allowed on all the Compute Constructs, Data Constructs, Executable Constructs,...
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:36
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:55
@ TST_decltype
Definition: Specifiers.h:89
@ TST_typename_pack_indexing
Definition: Specifiers.h:97
@ TST_decltype_auto
Definition: Specifiers.h:93
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
@ NUM_OVERLOADED_OPERATORS
Definition: OperatorKinds.h:26
bool isa(CodeGen::Address addr)
Definition: Address.h:294
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:209
@ CPlusPlus23
Definition: LangStandard.h:60
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus14
Definition: LangStandard.h:57
@ CPlusPlus26
Definition: LangStandard.h:61
@ CPlusPlus17
Definition: LangStandard.h:58
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition: Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition: Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition: Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition: Overload.h:55
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
LinkageSpecLanguageIDs
Represents the language in a linkage specification.
Definition: DeclCXX.h:2923
InClassInitStyle
In-class initialization styles for non-static data members.
Definition: Specifiers.h:268
@ ICIS_ListInit
Direct list-initialization.
Definition: Specifiers.h:271
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:269
@ RQ_None
No ref-qualifier was provided.
Definition: Type.h:1556
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1562
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition: Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition: Overload.h:67
CXXConstructionKind
Definition: ExprCXX.h:1532
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:148
BinaryOperatorKind
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
@ IK_TemplateId
A template-id, e.g., f<int>.
@ IK_ConstructorTemplateId
A constructor named via a template-id.
@ IK_ConstructorName
A constructor name.
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
@ IK_Identifier
An identifier.
@ IK_DestructorName
A destructor name.
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
std::optional< ComparisonCategoryType > getComparisonCategoryForBuiltinCmp(QualType T)
Get the comparison category that should be used when comparing values of type T.
StorageClass
Storage classes.
Definition: Specifiers.h:245
@ SC_Static
Definition: Specifiers.h:249
@ SC_None
Definition: Specifiers.h:247
ThreadStorageClassSpecifier
Thread storage-class-specifier.
Definition: Specifiers.h:232
ComparisonCategoryType commonComparisonType(ComparisonCategoryType A, ComparisonCategoryType B)
Determine the common comparison type, as defined in C++2a [class.spaceship]p4.
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:54
Language
The language for the input, used to select and validate the language standard and possible actions.
Definition: LangStandard.h:23
StmtResult StmtError()
Definition: Ownership.h:265
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
void EscapeStringForDiagnostic(StringRef Str, SmallVectorImpl< char > &OutStr)
EscapeStringForDiagnostic - Append Str to the diagnostic buffer, escaping non-printable characters an...
Definition: Diagnostic.cpp:805
ReservedLiteralSuffixIdStatus
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
TagTypeKind
The kind of a tag type.
Definition: Type.h:6099
@ Interface
The "__interface" keyword.
@ Struct
The "struct" keyword.
@ Class
The "class" keyword.
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:262
ExprResult ExprError()
Definition: Ownership.h:264
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
@ CanPassInRegs
The argument of this type can be passed directly in registers.
@ CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
@ CannotPassInRegs
The argument of this type cannot be passed directly in registers.
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
Definition: LangOptions.h:1076
ComparisonCategoryType
An enumeration representing the different comparison categories types.
ActionResult< Stmt * > StmtResult
Definition: Ownership.h:249
CXXSpecialMemberKind
Kinds of C++ special members.
Definition: Sema.h:432
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
Definition: OperatorKinds.h:36
@ TNK_Concept_template
The name refers to a concept.
Definition: TemplateKinds.h:52
ActionResult< ParsedType > TypeResult
Definition: Ownership.h:250
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:129
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:141
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
const FunctionProtoType * T
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1277
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:185
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:203
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:199
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:195
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:191
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:188
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:6074
@ None
No keyword precedes the qualified type name.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
bool isExternallyVisible(Linkage L)
Definition: Linkage.h:90
@ Other
Other implicit parameter.
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ EST_DynamicNone
throw()
@ EST_Uninstantiated
not instantiated yet
@ EST_Unparsed
not parsed yet
@ EST_NoThrow
Microsoft __declspec(nothrow) extension.
@ EST_None
no exception specification
@ EST_MSAny
Microsoft throw(...) extension.
@ EST_BasicNoexcept
noexcept
@ EST_NoexceptFalse
noexcept(expression), evals to 'false'
@ EST_Unevaluated
not evaluated yet, for special member function
@ EST_NoexceptTrue
noexcept(expression), evals to 'true'
@ EST_Dynamic
throw(T1, T2)
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:120
@ AS_public
Definition: Specifiers.h:121
@ AS_protected
Definition: Specifiers.h:122
@ AS_none
Definition: Specifiers.h:124
@ AS_private
Definition: Specifiers.h:123
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:258
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition: Specifiers.h:174
unsigned long uint64_t
long int64_t
float __ovld __cnfn distance(float, float)
Returns the distance between p0 and p1.
#define true
Definition: stdbool.h:21
#define false
Definition: stdbool.h:22
bool hasValidIntValue() const
True iff we've successfully evaluated the variable as a constant expression and extracted its integer...
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setNamedTypeInfo(TypeSourceInfo *TInfo)
setNamedTypeInfo - Sets the source type info associated to the name.
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
SourceRange getSourceRange() const LLVM_READONLY
getSourceRange - The range of the declaration name.
SourceLocation getEndLoc() const LLVM_READONLY
bool containsUnexpandedParameterPack() const
Determine whether this name contains an unexpanded parameter pack.
unsigned isVariadic
isVariadic - If this function has a prototype, and if that proto ends with ',...)',...
Definition: DeclSpec.h:1364
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition: DeclSpec.h:1424
unsigned RefQualifierIsLValueRef
Whether the ref-qualifier (if any) is an lvalue reference.
Definition: DeclSpec.h:1373
DeclSpec * MethodQualifiers
DeclSpec for the function with the qualifier related info.
Definition: DeclSpec.h:1427
SourceLocation getRefQualifierLoc() const
Retrieve the location of the ref-qualifier, if any.
Definition: DeclSpec.h:1525
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1399
bool hasMutableQualifier() const
Determine whether this lambda-declarator contains a 'mutable' qualifier.
Definition: DeclSpec.h:1554
bool hasMethodTypeQualifiers() const
Determine whether this method has qualifiers.
Definition: DeclSpec.h:1557
void freeParams()
Reset the parameter list to having zero parameters.
Definition: DeclSpec.h:1463
bool hasRefQualifier() const
Determine whether this function declaration contains a ref-qualifier.
Definition: DeclSpec.h:1550
std::unique_ptr< CachedTokens > DefaultArgTokens
DefaultArgTokens - When the parameter's default argument cannot be parsed immediately (because it occ...
Definition: DeclSpec.h:1339
One instance of this struct is used for each type in a declarator that is parsed.
Definition: DeclSpec.h:1247
enum clang::DeclaratorChunk::@219 Kind
FunctionTypeInfo Fun
Definition: DeclSpec.h:1638
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
Holds information about the various types of exception specification.
Definition: Type.h:4507
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition: Type.h:4519
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:4509
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:4512
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition: Type.h:4515
Extra information about a function prototype.
Definition: Type.h:4535
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:4542
FunctionType::ExtInfo ExtInfo
Definition: Type.h:4536
T * get(ExternalASTSource *Source) const
Retrieve the pointer to the AST node that this lazy pointer points to.
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition: Overload.h:1006
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:9997
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition: Sema.h:10114
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition: Sema.h:10091
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition: Sema.h:10088
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition: Sema.h:10041
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition: Sema.h:10055
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition: Sema.h:10059
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:10117
CXXSpecialMemberKind SpecialMember
The special member being declared or defined.
Definition: Sema.h:10143
Abstract class used to diagnose incomplete types.
Definition: Sema.h:6548
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T)=0
Information about a template-id annotation token.
TemplateNameKind Kind
The kind of template that Template refers to.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
OpaquePtr< T > get() const
Definition: Ownership.h:104